Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select DISTINCT rows without having the ORDER BY field selected

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.

like image 586
Jannie Theunissen Avatar asked Feb 03 '26 18:02

Jannie Theunissen


1 Answers

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
like image 190
Anthony Faull Avatar answered Feb 06 '26 06:02

Anthony Faull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!