如果你沒有一個唯一約束(user_id, timestamp)
但你仍然要保證只有一個行每個用戶返回,那麼你可以使用此查詢:
SELECT id, user_id, status_text, timestamp
FROM (
SELECT *, @prev <> user_id AS is_newest, @prev := user_id
FROM user_log, (SELECT @prev := -1) AS vars
ORDER BY user_id, timestamp DESC, id DESC
) AS T1
WHERE is_newest
結果:
1, 1, 'Foo', '2010-01-01 00:00'
4, 2, 'Bar', '2010-01-01 01:00'
測試數據:
CREATE TABLE user_log (id INT NOT NULL, user_id INT NOT NULL, status_text NVARCHAR(100) NOT NULL, timestamp NVARCHAR(100) NOT NULL);
INSERT INTO user_log (id, user_id, status_text, timestamp) VALUES
(1, 1, 'Foo', '2010-01-01 00:00'),
(2, 1, 'Bar', '2010-01-01 00:00'),
(3, 2, 'Foo', '2010-01-01 00:00'),
(4, 2, 'Bar', '2010-01-01 01:00');
您是否只想要user_id和date或任何支持行? – 2010-04-06 20:36:36
在user_id,timestamp上是否存在唯一約束? – 2010-04-06 20:36:49