• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

Selecting from one table, ordering according to other one

tbl_rides: ID | more_fields
tbl_results: rideID | rank | more_fields

SELECT * FROM tbl_rides WHERE ID IN (SELECT rideID FROM tbl_results)

I need to order the above statement according to tbl_results.rank field desc. (Higher rank appears top). How is it done?

Using MS ACCESS
0
shmulik15
Asked:
shmulik15
1 Solution
 
Rey Obrero (Capricorn1)Commented:
try this


SELECT tbl_rides.* , tbl_results.rank
FROM tbl_rides
inner join tbl_results on
tbl_rides.ID=tbl_results.rideID
order by tbl_results.rank desc
0
 
Bill BachPresidentCommented:
With SQL, you are dealing with "unordered sets" of data.  Therefore, when you build the set of data for the inner SELECT statement, order is meaningless.

To get the data exactly in the order you need, you must join the two sets first, then apply the order by, and then select out your fields.  It would look like this:

SELECT tbl_rides.*
FROM tbl_rides
INNER JOIN tbl_results ON tbl_rides.ID = tbl_results.rideID
ORDER BY tbl_results.rank

Please note that this may NOT give you back the exact same data set, as it may duplicate some data, you you may need to add a DISTINCT clause to it, but this will get you close.
0
 
Mark WillsTopic AdvisorCommented:
If you want only those rows in tbl_rides where an ID exists in tbl_results, then an inner join is the way to go. Otherwise you may want to consider a left outer join...

and just realised I type the same code as capricorn1 for the inner join...

SELECT tbl_rides.* , tbl_results.rank
FROM tbl_rides
inner join tbl_results on tbl_rides.ID=tbl_results.rideID
order by rank desc

so, the outer join, putting unranked rides at the bottom...

SELECT tbl_rides.* , iif( isnull(tbl_results.rank),0,tbl_results.rank) as RANK
FROM tbl_rides
left outer join tbl_results on tbl_rides.ID=tbl_results.rideID
order by rank desc
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
just for the "fun", you CAN of course do it without a "join" :)
SELECT r.* 
FROM tbl_rides r
WHERE r.ID IN (SELECT rideID FROM tbl_results)
ORDER BY (SELECT TOP 1 rank FROM tbl_results re WHERE re.rideID = r.ID )
 
resp with a exists:
 
SELECT r.* 
FROM tbl_rides r
WHERE EXISTS( SELECT null FROM tbl_results re WHERE re.rideID = r.ID )
ORDER BY (SELECT TOP 1 rank FROM tbl_results re WHERE re.rideID = r.ID )

Open in new window

0
 
shmulik15Author Commented:
Thanks a lot, your help is appreciated.
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now