Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - order by statement

I've got tables like:

table A
id name   email
1  test1  [email protected]
2  test2  [email protected]
3  test3  [email protected]
4  test4   ....
5  test5   ....

table B
id catA    catB   year member 
1  false   true   2011  2
2  true    false  2011  3
3  fals    true   2010  5

And i want to get every row in table A and sort it by following:

FIRST, get user 2 (current year, based on table B)
SECOND, get user 3 (current year, based on table B)
after that get users that is in table B
after that get all other users.

I know that i can have specific sql for getting the first two users, and the just the rest. But shouldnt i be able to get them all with a nice ORDER by statement? Like limiting the first order statement to just affect the first row...

like image 696
joxxe Avatar asked Oct 09 '22 15:10

joxxe


1 Answers

Something like this?

select A.id, A.name, A.email, B.catA, B.catB, B.year
from A
join B on A.id = B.member
ORDER BY B.year DESC, (B.member IS NOT NULL) DESC

First sort all results by the year field in table B, which gets you 2011, 2010, etc... Any members who are NOT listed in table B will have a null year and sort to the bottom of the list. Next sort by B.member not being null - mysql will coerce this boolean result into an integer 1 or 0, which can be sorted, So sort descending to make all the 1's (not null B.members) sort first.

like image 110
Marc B Avatar answered Oct 12 '22 23:10

Marc B