代码之家  ›  专栏  ›  技术社区  ›  Zero

优化“不在”查询

sql
  •  2
  • Zero  · 技术社区  · 15 年前

    请帮助优化此查询:

    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
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Eric Mickelsen    15 年前
    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
    
        2
  •  0
  •   Irawan Soetomo    15 年前

    
    ;
    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