views:

320

answers:

6

So I have two tables students (PK sID) and mentors (PK pID). This query

SELECT s.pID
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE '%a%'
ORDER BY s.sID DESC;

delivers this result

pID
-------------
9
9
3
9
3
9
9
9
10
9
3
10  etc...

I am trying to get a list of distinct mentor ID's with this ordering so I am looking for the SQL to produce

pID
-------------
9
3
10

If I simply insert a DISTINCT in the SELECT clause I get an unexpected result of 10, 9, 3 (wrong order). Any help much appreciated.

+5  A: 

You can't receive records in any predefined order if you don't use ORDER BY because then the DB engine decides in what order to return them.

wRAR
I'm using ORDER BY
JannieT
+2  A: 

Try this:

SELECT s.pID
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE '%a%'
GROUP BY s.pID
ORDER BY s.sID DESC;

I.e. GROUP BY instead of DISTINCT should preserve order.

dkamins
i check it with group by it's not working according to requirement.
Salil
I've tried this before posting the question. When there are no aggregating functions in the SELECT clause GROUP BY works exactly like DISTINCT according to some expert comments on similar topics here
JannieT
A: 

After using distinct "ORDER BY s.sID DESC;" will not work so try using somwthing like following

SELECT distinct(s.pID) as PID
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE '%a%'
ORDER BY PID;

This will return >> 3, 9, 10

Salil
Expected order is 9 3 10
Nitin Midha
A: 

Use this

SELECT DISTINCT s.pID as PID
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE '%a%'
ORDER BY s.sID DESC,1;
Veer
This gives 3,9,10
JannieT
A: 

After struggling some more I have this

SELECT s.pID, MAX(s.sID) AS newest_student
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE '%a%'
GROUP BY s.pID
ORDER BY newest_student DESC;

which gives me the required 9,3,10 but I have one useless field returned with it. I am hoping some-one will come with a better solution.

JannieT
+1  A: 
SELECT s.pID
FROM students s JOIN mentors m ON s.pID = m.pID   
WHERE m.tags LIKE '%a%'
GROUP BY s.pID
ORDER BY MAX(s.sID) DESC
Anthony Faull
Brilliant! Thanks a lot.
JannieT