2

考虑以下 Table_A 和 Table_B:

Table_A
ID  |A_Field_1
1   |10
2   |11
3   |12

表_B:

ID  |B_Field_1
1   |500
1   |510
1   |520
2   |550
3   |530

我需要编写一个查询 where in 来获取IDA_Field_1for 值中Table_B没有B_Field_1520 或 530 的值。

输出:

ID  |A_FIELD_1
2   |11

我目前的查询如下:

SELECT ID,A_Field_1 
from Table_A
where ID not in (select ID from Table_B where B_Field_1 in (520,530))

这可行,但有人可以提供更好的基于性能的查询吗?与上面的查询一样,select ID from Table_B where B_Field_1 in (520,530)内部查询很大并且对应于一个不断增长的表。

4

2 回答 2

2

试试这个——

SELECT
      Id
    , A_Field_1
FROM Table_A a
WHERE EXISTS(
          SELECT 1
          FROM Table_B b
          WHERE B_Field_1 NOT IN (520, 530)
               AND b.Id = a.Id
     )


SELECT
      Id
    , A_Field_1
FROM Table_A a
WHERE NOT EXISTS(
          SELECT 1
          FROM Table_B b
          WHERE B_Field_1 IN (520, 530)
               AND b.Id = a.Id
     )
于 2013-07-01T05:41:14.140 回答
2

你也可以这样试试

SELECT
      Id
    , A_Field_1
FROM TABLE_A A
INNER JOIN
(
     SELECT
           Id
         , COUNT(CASE WHEN B_Field_1 IN (520, 530) THEN 1 END) AS ValidId
     FROM Table_B
     GROUP BY Id
) b ON A.Id = b.Id AND b.ValidId < 1
于 2013-07-01T05:48:58.487 回答