从mysql中的两个表中查找最近的行

时间:2013-06-24 10:39:51

标签: mysql join

我有2张桌子

表A

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中没有数据,我找不到最新的收入。

谢谢

3 个答案:

答案 0 :(得分: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演示。

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分: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