抛出旧版和旧版行的SQL查询满足条件?

时间:2009-09-14 04:57:44

标签: sql mysql

发出以下查询:

  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 |
+-------------+------------------------+------+------+---------------------+

我想根据这个条件返回行:

  1. 如果有重复的行具有相同的 buddyId ,则只返回最新的(由 dtCreated 指定)。
  2. 所以,查询应该返回我:

    +-------------+------------------------+------+------+---------------------+
    |         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函数没有成功,但它无法正常工作。

1 个答案:

答案 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;