2012-07-05 187 views
0

我有两个表,可以说table1和table2具有公共列id和update_date。我正在寻找基于最新的update_date降序的ID和update_date。我一起使用'union'和'order by',它们以update_date的降序给出了结果,但是有重复的id,我不知道如何去除。在使用UNION和ORDER的mysql查询中避免重复

我的查询是什么样子,

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

我可以得到由(上述查询),作为临时选择加入不同的ID去掉重复的ID的;但问题是我也需要update_date。

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

+0

我希望这下面的链接可能会有所帮助。 http://stackoverflow.com/questions/7640396/removing-duplicate-results-while-using-union-select – GoutamS 2016-12-21 12:52:18

回答

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 
+0

感谢您的最大()建议。我改变了查询来摆脱模棱两可的列错误。我工作的修改版本是: select(select_id,update_date from table1 where [condition])UNION(select id,update_date from table2 where [condition])order by update_date DESC)as临时组通过ID; – 2012-07-05 16:13:58

0

包裹查询在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; 
+0

谢谢。这不起作用,因为对于相同的id,两个表中的update_date可能不同。所以不同的是返回所有行。 – 2012-07-05 15:48:56

0

限制第二查询的结果:

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]) 
+0

问题是我必须得到id和“最新”update_date。例如,同一个id在这两个表中可以有不同的update_date。所以我必须在两个表中获取该id的最新update_date。 – 2012-07-05 15:53:46