Syntax

編寫多個“AND”的更有效方法?

  • January 10, 2014

有誰知道用不同的方式寫這個?

SELECT tableA.NO
FROM tableA
WHERE tableA.NO IN (SELECT GRI_NO FROM tableBB WHERE GRO_NO =62)
 AND tableA.NO IN (SELECT GRI_NO FROM tableBB WHERE GRO_NO =50)
 AND tableA.NO IN (SELECT GRI_NO FROM tableBB WHERE GRO_NO =70)

我還有更多 AND 要添加,它變成了一個很長的查詢。 是否存在**等價物?WHERE GRO_NO IN (62, 50, 70)``AND

編輯如下:

sampleA1 的等效項是關鍵字的 sampleA2 OR

樣品A1:WHERE GRO_NO IN (62, 50, 70)

樣品A2:WHERE GRO_NO =62 OR GRO_NO =50 OR GRO_NO =70)

關鍵字是否存在等效的 sampleB2 AND

樣品B2:WHERE GRO_NO =62 AND GRO_NO =50 AND GRO_NO =70)


Edit2:我刪除了性能標籤,因為它與清晰度/語法/更短的 sql比數據庫性能更相關。

不確定這是否比您擁有的更快,但您可以嘗試

SELECT tableA.NO
FROM tableA
WHERE tableA.NO
IN 
(
  SELECT GRI_NO FROM tableBB WHERE GRO_NO IN (62,50,70) 
  GROUP BY GRI_NO
  HAVING COUNT(DISTINCT GRO_NO) =3
)

我建議join用 group by 和有或exists檢查進行檢查

加入

SELECT tableA.NO
FROM tableBB 
   JOIN tableA ON tableA.NO = tableBB.GRI_NO
WHERE 
   tableBB.GRO_NO IN (62,50,70)
GROUP BY tableA.NO
HAVING COUNT(DISTINCT tableBB.GRO_NO) = 3 /* specify the count of GRO_NO's required */

EXISTS檢查可以與現有的 AND 檢查一起使用(在 OP 問題中)

SELECT tableA.NO
FROM tableA
WHERE 
   EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 62)
   AND EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 50)
   AND EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 70)

根據您的數據分佈,您應該會發現其中一個會執行得更快。

如果您需要擴展特定 GRO_NO 的標準,即:對於 70,請檢查 IsActive=1,您可以執行以下操作:

加入

SELECT tableA.NO
FROM tableBB 
   JOIN tableA ON tableA.NO = tableBB.GRI_NO
WHERE 
   tableBB.GRO_NO IN (62,50,70)
   /* GRO_NO specific clause */
   AND ((tableBB.GRO_NO = 70 AND tableBB.IsActive = 1) OR tableBB.GRO_NO != 70)
GROUP BY tableA.NO
HAVING COUNT(DISTINCT tableBB.GRO_NO) = 3 /* specify the count of GRO_NO's required */

存在

SELECT tableA.NO
FROM tableA
WHERE 
   EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 62)
   AND EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 50)
   AND EXISTS (SELECT 'NO is in tableBB' FROM tableBB 
           WHERE tableA.NO = tableBB.GRI_NO AND tableBB.GRO_NO = 70 
                AND tableBB.IsActive = 1)

引用自:https://dba.stackexchange.com/questions/56466