2012-07-05 178 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