【问题标题】:Avoiding duplicates in mysql query that uses UNION and ORDER BY在使用 UNION 和 ORDER BY 的 mysql 查询中避免重复
【发布时间】:2012-07-06 01:24:52
【问题描述】:

我有两个表,假设 table1 和 table2 有公共列,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 distinct id from (above query) 添加为 temp 来摆脱重复的 id;但问题是我也需要 update_date。

任何人都可以建议如何摆脱重复并仍然获得 id 和 update_date 信息。

【问题讨论】:

标签: mysql duplicate-removal


【解决方案1】:

假设您希望从重复项中获取最新更新,这应该可以工作:

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

【讨论】:

  • 感谢 max() 的建议。我更改了查询以消除模棱两可的列错误。对我有用的修改版本是: select id, max(update_date) from ((select id,update_date from table1 where [condition]) UNION (select id,update_date from table2 where [condition]) order by update_date DESC) as temp按 ID 分组;
【解决方案2】:

将查询包装在 DISTINCT 块中:

SELECT DISTINCT * FROM (
  select id,update_date from table1 where [condition]
  UNION
  select id,update_date from table2 where [condition]
)
order by update_date desc;

【讨论】:

  • 谢谢。这不起作用,因为相同 id 的两个表中的 update_date 可能不同。如此不同的是返回所有行。
【解决方案3】:

限制第二个查询的结果:

select id, update_date
  from table1
 where [conditions]
union
select id, update_date
  from table2
 where [conditions]
   and id not in (select id from table1 where [conditions])

【讨论】:

  • 问题是我必须得到 id 和“最新的”update_date。例如,同一个 id 在这两个表中可以有不同的 update_date。所以我必须在两个表中获取该 id 的最新 update_date。
猜你喜欢
  • 2019-08-26
  • 2011-12-20
  • 2014-05-30
  • 2010-09-17
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
相关资源
最近更新 更多