2013-06-24 24 views
-1

兩個表最近的行我有2個表找到在MySQL

表一

id  user_id created_date earning 
1   5  2013-05-05  500 
2   4  2013-06-02  900 
3   3  2013-03-01  700 

表B中

id  user_id created_date earning 
1   8  2013-09-05  500 
2   4  2013-08-12  200 
3   3  2013-02-21  200 

具有相同的字段。

我想要的是爲用戶找到最新的收入。對於用戶3,我可以找到最新的收入,但對於用戶8,表A中沒有數據,我找不到最新的收入。

謝謝

+1

但對於用戶4數據表a。 –

+0

你能告訴我們你到目前爲止做了什麼嗎? – KaeL

+0

這兩個表都有user_id = 4的數據。 – ABorty

回答

1
SELECT T.user_id 
    , CAST(SUBSTRING_INDEX(GROUP_CONCAT(T.earning ORDER BY T.created_date DESC), ',', 1) AS DECIMAL) AS latest_earning 
    FROM (
     SELECT user_id 
      , created_date 
      , earning 
      FROM tableA 

     UNION ALL 

     SELECT user_id 
      , created_date 
      , earning 
      FROM tableB 
    ) T 
    GROUP BY T.user_id; 

這裏是SQL Fiddle演示。

0

試試這個:

select * from (
    select * from (
    select * from tablea 
    union 
    select * from tableb) x 
    order by created_date desc) y 
group by user_id 
+0

嗨,你需要使用'聯合所有','聯盟'刪除重複的行。 – KaeL

+0

@KaeL刪除重複對結果沒有任何影響。此查詢爲每個用戶返回一行。保持重複會得到相同的結果。 – Bohemian

+0

它會產生影響,'UNION'可能會從'created_date'列中刪除最新的記錄庫。你會得到不正確的'賺錢'。 – KaeL

0

假設有永遠只能1爲用戶收入在某一特定日期,你可以使用以下命令: -

SELECT Sub4.id, Sub4.user_id, Sub4.created_date, Sub4.earning 
FROM (SELECT user_id, MAX(created_date) AS MaxCreatedDate 
FROM (SELECT user_id, created_date 
FROM tableA 
UNION ALL 
SELECT user_id, created_date 
FROM tableB) Sub1) Sub2 
INNER JOIN (SELECT user_id, created_date, earning 
FROM tableA 
UNION ALL 
SELECT user_id, created_date, earning 
FROM tableB) Sub4 
ON Sub2.user_id = Sub4.user_id 
AND Sub2.MaxCreatedDate = Sub4.created_date