2010-12-07 35 views
1

我已經搜索,但無法壓縮足以找到相關答案的問題。我的經驗告訴我這可能是一個設計問題...在MySql中複雜的一對多查詢

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 

但是,是否真的是這樣做的準確方法,因爲如果我想返回多個用戶呢?

任何幫助將不勝感激。

回答

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' 
+0

謝謝。除了SELECT語句外,我在每個地方都使用了子查詢。這就像一個魅力。 – csi 2010-12-07 18:00:21

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)) 
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