使用多个条件和变量进行SQL查询更有效

时间:2016-01-08 15:13:58

标签: sql sql-server

我有这个查询确实得到了我需要的结果,但速度非常慢,肯定必须有一个更好的方法,因为我需要定期运行。

每个where子句有两个变量,它们总是相同的数字,但我需要使用50个以上的BigID,示例显示3但我会为BigID 1到50+。

由于两个变量(其中一个在子查询中)和需要的组,我不确定如何缩短它。 任何帮助或指向正确的方向将不胜感激。感谢。

 SELECT BigID,count(LittleID)
      FROM Table1
      where ( (BigID=1 and LittleID not in (SELECT LittleID FROM Table2 where BigID=1)) or
              (BigID=2 and LittleID not in (SELECT LittleID FROM Table2 where BigID=2)) or
              (BigID=3 and LittleID not in (SELECT LittleID FROM Table2 where BigID=3)) )
      group by BigID

3 个答案:

答案 0 :(得分:2)

一种方法是相关子查询:

  SELECT t1.BigID, count(t1.LittleID)
  FROM Table1 t1
  WHERE t1.BigID IN (1, 2, 3) and
        t1.LittleID not in (SELECT t2.LittleID
                            FROM Table2 t2
                            WHERE t2.BigID = t1.BigId
                           )
  GROUP BY t1.BigID

答案 1 :(得分:1)

SELECT t1.BigID, COUNT(t1.LittleID)
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.LittleID = t2.LittleID AND t1.BigID = t2.BigID
WHERE t1.BigID IN (1, 2, 3)
    AND t2.LittleID IS NULL
GROUP BY t1.BigID

答案 2 :(得分:1)

SELECT Table1.BigID,
       COUNT(Table1.LittleID)
FROM Table1
LEFT JOIN Table2 ON Table1.LittleID = Table2.LittleID
    AND Table1.BigID = Table2.BigID
WHERE Table2.LittleID IS NULL
    AND Table1.BigID IN (1, 2, 3)
GROUP BY Table1.BigID