MySQL在使用UNION时使用ORDER BY

时间:2013-04-27 10:27:58

标签: mysql sql-order-by

我正在尝试显示一个用户列表,其中activated=1帐户列表低于activated=0帐户,而UNION帐户位于最高位置。我尝试使用ORDER BY created DESC,因为我需要将所有非活动帐户设为ORDER BY email,而激活的帐户设置为ORDER BY但由于某种原因,我的所有( SELECT email, roles.full role, created FROM sol_users users JOIN sol_user_roles ur ON users.id = ur.user_id JOIN sol_roles roles USING(role_id) WHERE activated = 0 ORDER BY created DESC ) UNION ( SELECT email, roles.full role, created FROM sol_users users JOIN sol_user_roles ur ON users.id = ur.user_id JOIN sol_roles roles USING(role_id) WHERE activated = 1 ORDER BY email ) 命令都被忽略。我在这里做错了什么?

{{1}}

需要将非活动用户置于最顶层,以便管理员知道这些需要激活。

2 个答案:

答案 0 :(得分:2)

你不需要工会 - 试试:

SELECT email, roles.full role, created 
FROM sol_users users
JOIN sol_user_roles ur ON users.id = ur.user_id 
JOIN sol_roles roles USING(role_id) 
ORDER BY activated, case activated when 1 then email end, created DESC

答案 1 :(得分:0)

您可以尝试在IF子句中使用ORDER BY语句。有关类似主题的讨论,请参阅this