2010-12-08 33 views
1

我想編寫一個查詢,我想獲得用戶的最後「專項行動」的列表,最近的操作,所以我有這些表:MySQL的:讓每

table_users 
id  username  email   etc. 
1  moloc  [email protected]  etc. 
2  lilly  [email protected]  etc. 
3  sammm  [email protected]  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的一個,而不是相對於正確的日期行。

我在哪裏錯了?

+0

更改action_id,max(日期)到max(action_id)作爲action_id,max(日期)作爲action_date並且請不要使用保留字作爲字段名 - arghh – 2010-12-08 21:30:28

回答

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

謝謝你,你已經解決了一個問題。兩天,一個簡單而線性的解決方案。 – vitto 2010-12-08 22:22:15

0

,因爲你使用的聚合函數(MAX)你有這樣的結果可能是,只有通過第一列(user_id)分組和左起第二列(action_id)進行分組和彙總。