我想編寫一個查詢,我想獲得用戶的最後「專項行動」的列表,最近的操作,所以我有這些表: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的一個,而不是相對於正確的日期行。
我在哪裏錯了?
更改action_id,max(日期)到max(action_id)作爲action_id,max(日期)作爲action_date並且請不要使用保留字作爲字段名 - arghh – 2010-12-08 21:30:28