2009-09-14 69 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