MySQL:获取每行最新的操作

时间:2010-12-08 21:09:55

标签: mysql subquery

我正在尝试编写一个查询,我想获取用户最后一次“特殊操作”的列表,所以我有这些表:

table_users
id     username     email          etc.
1      moloc        a@mail.com     etc.
2      lilly        b@mail.com     etc.
3      sammm        c@mail.com     etc.


table_special_actions
id     user_id      action_id      date
1      3            25             2010-11-01 22:51:56
2      3            37             2010-11-02 18:09:33
3      3            265            2010-11-03 07:20:12


table_actions
id        action
1         Open a secret
2         Level up
3         Open magic door
etc.      etc.

我的目标是获取一个用户列表,其中我只有每个人的最后一个特殊操作,所以我想到这样的事情:

SELECT *
FROM table_users AS users
LEFT JOIN (
    SELECT user_id, action_id, MAX(date) AS action_date
    FROM table_special_actions
    GROUP BY user_id
    ORDER BY action_date
) s_actions
ON s_actions.user_id = users.user_id
LEFT JOIN table_actions AS actions
ON s_actions.action_id = actions.id

这不能正常工作,因为它会返回:

-----users-----    ------------s_actions------------    -----actions-----
id     username    action_id     date                   action
3      sammm       25            2010-11-03 07:20:12    Action linked to action_id 25

我期望得到这个:

-----users-----    ------------s_actions------------    -----actions-----
id     username    action_id     date                   action
3      sammm       265           2010-11-03 07:20:12    Action linked to action_id 265

奇怪的是action_id,我总是得到最后的日期,这没关系,但我也总是得到第一个action_id而不是相对于正确日期行的那个。

我哪里错了?

2 个答案:

答案 0 :(得分:2)

你很亲密。尝试:

SELECT *
    FROM table_users AS users
        LEFT JOIN (SELECT user_id, MAX(date) AS MaxDate
                       FROM table_special_actions
                       GROUP BY user_id) s_actions
            ON s_actions.user_id = users.user_id
        LEFT JOIN table_special_actions s2_actions
            ON s_actions.userid = s2_actions.id
                AND s_actions.MaxDate = s2_actions.date
        LEFT JOIN table_actions AS actions
            ON s2_actions.action_id = actions.id

答案 1 :(得分:0)

您得到此结果可能是因为您使用了聚合函数(MAX)并仅按第一列(user_id)分组,并将第二列(action_id)排除在分组之外和聚合。