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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With