发出以下查询:
SELECT t.seq,
t.buddyId,
t.mode,
t.type,
t.dtCreated
FROM MIM t
WHERE t.userId = 'ali'
ORDER BY t.dtCreated DESC;
...给我6行。
+-------------+------------------------+------+------+---------------------+
| seq | buddyId | mode | type | dtCreated |
+-------------+------------------------+------+------+---------------------+
| 12 | abcdefghij25@gmail.com | 2 | 1 | 2009-09-14 12:39:05 |
| 11 | abcdefghij25@gmail.com | 4 | 1 | 2009-09-14 12:39:02 |
| 10 | op_eee_81@hotmail.com | 1 | -1 | 2009-09-14 12:39:00 |
| 9 | abcdefghij25@gmail.com | 1 | -1 | 2009-09-14 12:38:59 |
| 8 | op_eee_81@hotmail.com | 2 | 1 | 2009-09-14 12:37:53 |
| 7 | abcdefghij25@gmail.com | 2 | 1 | 2009-09-14 12:37:46 |
+-------------+------------------------+------+------+---------------------+
我想根据这个条件返回行:
所以,查询应该返回我:
+-------------+------------------------+------+------+---------------------+
| seq | buddyId | mode | type | dtCreated |
+-------------+------------------------+------+------+---------------------+
| 12 | abcdefghij25@gmail.com | 2 | 1 | 2009-09-14 12:39:05 |
| 10 | op_eee_81@hotmail.com | 1 | -1 | 2009-09-14 12:39:00 |
+-------------+------------------------+------+------+---------------------+
我尝试使用UNIQUE函数没有成功,但它无法正常工作。
答案 0 :(得分:2)
这应该只返回每个userId的最新条目。
SELECT a.seq
, a.buddyId
, a.mode
, a.type
, a.dtCreated
FROM mim AS [a]
JOIN (SELECT MAX(dtCreated) FROM min GROUP BY buddyId) AS [b]
ON a.dtCreated = b.dtCreated
AND a.userId = b.userId
WHERE userId='ali'
ORDER BY dtCreated DESC;