2
請幫助優化這個查詢:優化 「不是在」 查詢
SELECT ts.SiteId, COUNT(ts.SiteId) AS Count
FROM ts
WHERE ts.SiteId not in
(SELECT ts.SiteId FROM ts WHERE ts.uniqueid = 'xxx')
GROUP BY ts.SiteId ORDER BY Count DESC
請幫助優化這個查詢:優化 「不是在」 查詢
SELECT ts.SiteId, COUNT(ts.SiteId) AS Count
FROM ts
WHERE ts.SiteId not in
(SELECT ts.SiteId FROM ts WHERE ts.uniqueid = 'xxx')
GROUP BY ts.SiteId ORDER BY Count DESC
SELECT ts.SiteId, COUNT(ts.SiteId) AS Count,
MAX(CASE WHEN ts.uniqueid = 'xxx' THEN 1 ELSE 0 END) As XXXUniqueID
FROM ts
GROUP BY ts.SiteId
HAVING XXXUniqueID = 0
ORDER BY Count DESC
在SQL 2005 CTE,它可能是這樣的:
;
WITH
e AS
(
SELECT ts.SiteId FROM ts
EXCEPT
SELECT ts.SiteId FROM ts WHERE ts.uniqueid = 'xxx'
)
SELECT e.SiteId, COUNT(e.SiteId) AS Count
FROM e
GROUP BY e.SiteId ORDER BY Count DESC
這是我在想什麼。此外,如果您不想要返回額外列,則可以將整個「MAX(...)」表達式移動到「HAVING」子句中。 – VeeArr 2010-06-07 05:40:10
非常感謝。我用這樣的: SELECT ts.SiteId,COUNT(ts.SiteId)AS計數FROM TS GROUP BY ts.SiteId HAVING MAX(CASE WHEN ts.uniqueid = 'xxx' 的THEN ELSE 1 END 0)= 0 ORDER BY Count DESC – Zero 2010-06-07 05:50:36
我喜歡這個答案,但是我想從概念上知道爲什麼這樣做會更好。也許JOIN類型有所不同? – Daniel 2011-10-23 16:27:49