-1

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

谢谢你

4

3 回答 3

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演示。

于 2013-06-24T10:48:25.227 回答
0

试试这个:

select * from (
  select * from (
    select * from tablea
    union
    select * from tableb) x
  order by created_date desc) y
group by user_id
于 2013-06-24T10:54:44.153 回答
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
于 2013-06-24T12:58:09.007 回答