我有两个表,假设 table1 和 table2 具有公共(public)列 id 和 update_date。我希望根据最新的 update_date 按降序排列获取 id 和 update_date 。我一起使用了“union”和“order by”,这按 update_date 的降序给出了结果,但有重复的 id,我不知道如何摆脱。
我的查询是这样的,
(select id,update_date from table1 where [condition])
UNION
(select id,update_date from table2 where [condition])
order by update_date desc;
我可以通过添加 select different id from (above query) as temp 来消除重复的 id;但问题是我也需要 update_date。
任何人都可以建议如何删除重复项并仍然获取 id 和 update_date 信息。
最佳答案
假设您希望从重复项中获得最新更新,则此更新应该有效:
SELECT id, max(update_date) AS last_update
FROM
( (select id,update_date from table1 where [conditions])
UNION
(select id,update_date from table2 where [conditions]) ) both_tables
GROUP BY id
ORDER by last_update DESC
关于mysql - 避免使用 UNION 和 ORDER BY 的 mysql 查询中出现重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347742/