我有两张桌子:
users:
user_id user_name
data:
user_id user_data user_time
我想从数据表中选择最新的条目,但返回user_name, user_id, user_data
和user_time
。
我尝试了以下查询,但它返回第一个条目,而不是每个用户的最后一个:
sql = "SELECT users.user_name, users.user_id, data.user_data, data.user_time
FROM users
INNER JOIN data ON data.user_id = users.user_id
GROUP BY users.user_name
ORDER BY data.user_time DESC";
答案 0 :(得分:8)
使用GROUP BY和MAX,WHERE ... IN:
SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
INNER JOIN data d ON d.user_id = u.user_id
WHERE (d.user_id, d.user_time) =
(SELECT user_id, MAX(user_time) FROM data GROUP BY user_id)
我认为您最好将data_id
列添加到数据表中。
除非是data_id,PRIMARY KEY
都需要user_id和user_time(而user_time并不总是唯一的,不可靠的)
如果有data_id,可能很简单:
SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
INNER JOIN data d ON d.data_id =
(SELECT data_id FROM data
WHERE user_id = u.user_id ORDER BY data_time DESC LIMIT 1)