如何订购两个表结果MySql

时间:2017-09-07 08:33:51

标签: mysql sql

我从下面的查询中得到结果,我需要通过带有DESC顺序的id排序。如何在下面的查询中按功能添加订单。

SELECT * 
  FROM updated_post LEFT JOIN reporter_post ON updated_post.id = reporter_post.id 
UNION 
SELECT * 
  FROM reporter_post RIGHT JOIN updated_post ON reporter_post.id != updated_post.id

2 个答案:

答案 0 :(得分:2)

您需要执行以下操作:

  • 在查询中使用字段名称而不是*
  • UNION个查询换入另一个SELECT并应用ORDER BY

e.g:

SELECT * 
FROM (
    SELECT updated_post.id AS id, <other fields> 
      FROM updated_post LEFT JOIN reporter_post ON updated_post.id = 
    reporter_post.id 
    UNION 
    SELECT reporter_post.id AS id, <other fields> 
      FROM reporter_post RIGHT JOIN updated_post ON reporter_post.id != 
    updated_post.id
) a
ORDER BY a.id DESC;

答案 1 :(得分:1)

引用the documentation

  

要使用ORDER BYLIMIT子句对整个UNION结果进行排序或限制,请为各个SELECT语句添加括号并放置ORDER BY或{ {1}}在最后一个之后。

编辑:
结果中有两列名为LIMIT(如评论中所述) - idupdated_post.id。您应该完全限定其中一个(当然,根据reporter_post.id子句,它们是相同的)才能使用它:

所以,在你的情况下:

where