使用 UNION 合并两个 SELECT 查询的 ORDER BY

Combined ORDER BY of two SELECT queries using UNION

如何根据从 UNION 连接的这两个查询中检索到的结果获得组合顺序?

SELECT u.id, u.name, u.gender, n.user, n.other_user, n.type, n.notification, n.membership, n.link, n.created_at, p.photo FROM notifications n
INNER JOIN users u ON
CASE
  WHEN n.user = :me THEN u.id = n.other_user
  WHEN n.other_user = :me THEN u.id = n.user
END
LEFT JOIN photos p ON
CASE
  WHEN n.user = :me THEN p.user = n.other_user AND p.order_index = (SELECT MIN(order_index) FROM photos WHERE user = n.other_user)
  WHEN n.other_user = :me THEN p.user = n.user AND p.order_index = (SELECT MIN(order_index) FROM photos WHERE user = n.user)
END
UNION
SELECT '', '', '', '', '', '', n.notification, n.membership, n.link, n.created_at, '' FROM notifications n WHERE type = 'admin'

我希望返回的记录按照 id 降序排列。例如,如果从第一个查询返回的记录是 3,5,4,6,7 而从第二个查询返回的记录是 2,1,9 那么所有的记录应该像这样组合排序 9,7,6,5,4,3,2,1.

我试过这个:

SELECT * FROM
(

   *THE WHOLE QUERY ABOVE*

) AS x 
ORDER BY x.id

这没有返回正确的结果。它按降序 7,6,5,4,3 对第一个查询的结果进行排序,并按升序 1,2,9 对第二个查询的结果进行排序。他们正在单独排序,而不是一起排序。我怎样才能将它们组合在一起 9,7,6,5,4,3,2,1.

你自己已经发现问题了;您混淆了用户 ID 和通知 ID。所以 select 这两个,使用别名来区分和排序:

select u.id as user_id, ..., n.id as notification_id, ...
from ...
union all
select ... from ...
order by notification_id;

在两个查询中添加通知 ID 并给它们别名,因为您没有在表中使用别名(我猜)。然后只需使用“Thorsten Kettner”回答的通知 ID 的别名进行订购。

SELECT u.id as uid, n.id as nid, u.name, u.gender, n.user, n.other_user, n.type, n.notification, n.membership, n.link, n.created_at, p.photo FROM notifications n
INNER JOIN users u ON
CASE
  WHEN n.user = :me THEN u.id = n.other_user
  WHEN n.other_user = :me THEN u.id = n.user
END
LEFT JOIN photos p ON
CASE
  WHEN n.user = :me THEN p.user = n.other_user AND p.order_index = (SELECT MIN(order_index) FROM photos WHERE user = n.other_user)
  WHEN n.other_user = :me THEN p.user = n.user AND p.order_index = (SELECT MIN(order_index) FROM photos WHERE user = n.user)
END
UNION
SELECT '', n.id as nid, '', '', '', '', '', n.notification, n.membership, n.link, n.created_at, '' FROM notifications n WHERE type = 'admin'
ORDER BY nid DESC