MySQL:获取每行的最新操作

标签 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 而不是与正确日期行相关的那个。

我哪里错了?

最佳答案

你很接近。尝试:

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

关于MySQL:获取每行的最新操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4392361/

相关文章:

sql - 带有两个表的 MySQL 时间戳和 GROUP BY

PHP : Not able to call connection object

MYSQL连接子查询问题

mysql过程子查询返回多于1行

mySQL:如何过滤其他表中没有相同值的列?

mysql - 在SQL-Developer中选择MYSQL数据库

mysql - 子查询中的派生表无法访问主表

mysql - 选择具有 2 种排序类型的记录

ruby-on-rails - 使用带有事件记录的连接表时如何连接模型的多个实例?

postgresql - 避免 PostgreSQL 中的嵌套循环