2

我有两张桌子:

users:
user_id    user_name

data:
user_id    user_data    user_time

我想从数据表中选择最新的条目,但返回user_name, user_id, user_dataand 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";
4

1 回答 1

9

使用 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,否则 user_id 和 user_time 都是必需的PRIMARY KEY(并且 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) 
于 2012-04-25T20:52:21.997 回答