MySql中的一对多复杂查询

时间:2010-12-07 17:43:26

标签: mysql one-to-many

我已经搜索过,但无法将问题浓缩得足以找到相关答案。我的经验告诉我这可能是一个设计问题......

current_status
id
user_id
status_id
created

users
user_id
other...

current_status主要用于审计目的。每次用户状态更改时,都会在current_status中插入新记录。一些状态示例是“工作”,“解雇”,“应用”,“解雇”等。

查询 - 我想只返回每个用户的最新状态以及用户详细信息...

SELECT users.*, current_status.status_id AS status 
FROM users 
JOIN current_status ON users.user_id = current_status.user_id 
WHERE users.user_id = '1'

如何告诉查询返回用户的最新status_id?

ORDER BY current_status.created DESC LIMIT 0,1

然而,这是否真的是准确的方法,因为如果我想要返回多个用户呢?

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

编辑想想我现在掌握你的桌子/列......

SELECT    users.*,
         (SELECT   current_status.status_id
          FROM     current_status
          WHERE    current_status.user_id = users.user_id
          ORDER BY current_status.created DESC
          LIMIT    1) AS status
FROM      users
WHERE     users.user_id = '1'

EDITv2 此外,如果您想稍后加入表格以保存自己的查询,可以使用:

SELECT    users.*, current_status.*
FROM      users
  LEFT JOIN current_status
  ON        current_status.status_id = (
    SELECT   current_status.status_id
    FROM     current_status
    WHERE    current_status.user_id = users.user_id
    ORDER BY current_status.created DESC
    LIMIT    1
  )
WHERE     users.user_id = '1'

答案 1 :(得分:0)

也许是这样的?

SELECT users.*, current_status.status_id AS status
FROM
users,
current_status
WHERE users.user_id = '1' AND
users.user_id = current_status.user_id AND
current_status.status_id IN (SELECT max(status_id) FROM current_status GROUP_BY user_id))

答案 2 :(得分:0)

遗憾的是,MySQL并不支持over(order by ...)功能。这将采用子查询来选择所有最后的状态:

select 
  user.user_id, status.status_id, status.created
from user 
  join status on user.user_id = status.user_id
  join (
  select user_id, max(created)
  from status
  group by user_id
) last_status
on 
  status.user_id = last_statuses.user_id
    and status.created = last_statuses.created