2009-09-14 76 views
0

执行以下查询:SQL查询会抛弃较旧且满足条件的行吗?

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 | [email protected] | 2 | 1 | 2009-09-14 12:39:05 | 
|   11 | [email protected] | 4 | 1 | 2009-09-14 12:39:02 | 
|   10 | [email protected] | 1 | -1 | 2009-09-14 12:39:00 | 
|   9 | [email protected] | 1 | -1 | 2009-09-14 12:38:59 | 
|   8 | [email protected] | 2 | 1 | 2009-09-14 12:37:53 | 
|   7 | [email protected] | 2 | 1 | 2009-09-14 12:37:46 | 
+-------------+------------------------+------+------+---------------------+ 

我想返回基于此条件的行:

  1. 如果有与同一buddyId重复行,只返回我的最新(由指定dtCreated)。

因此,查询应该返回我:

+-------------+------------------------+------+------+---------------------+ 
|   seq | buddyId    | mode | type | dtCreated   | 
+-------------+------------------------+------+------+---------------------+ 
|   12 | [email protected] | 2 | 1 | 2009-09-14 12:39:05 | 
|   10 | [email protected] | 1 | -1 | 2009-09-14 12:39:00 | 
+-------------+------------------------+------+------+---------------------+ 

我没有成功尝试采用了独特的功能,但它不工作。

回答

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

我知道Where UserID =(select ....)的技巧,但它会为每一行运行子查询。这是更好的解决方案。 +1 – TheVillageIdiot 2009-09-14 05:16:51

+0

@TheVillageIdiot:对于WHERE子句中的每一行,子查询都不执行; SELECT子句中的SELECT(IE:SELECT t.col,(SELECT ...),...)**将** ... – 2009-09-14 05:21:51