I want to order a grouped statement using as reference the number choosen by an specific user.
SELECT * FROM likes WHERE /**/ GROUP BY type
TABLE
id_user type 1420 1 1421 3 1422 3 1424 7 1425 4 1426 2 1427 1
expected result (at the end what user 1425 choosed)
1 2 3 7 4 //choosen by id_user 1425
I want to put the last row with the number choosed by the user. i just cant figure that out
Advertisement
Answer
You can aggregate and use a conditional max
for ordering, like so:
select type from likes group by likes order by max(case when id_user = 1425 then 1 else 0 end), type
If any row for the given type
has an id_user
that matches the chosen value, the conditional max
returns 1
, wich puts it last in the resultset. The second ordering criteria break the ties for groups that do not fulfill the condition.
If you are running MySQL, you can simplify the order by
clause a little:
order by max(id_user = 1425), type