选择查询所需的性能

时间:2013-07-01 05:32:58

标签: sql performance select optimization informix

考虑以下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

我需要编写一个查询,其中可以获取IDA_Field_1Table_B的{​​{1}}值为520或530的值。< / p>

输出:

B_Field_1

我目前的查询如下:

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)) 内部查询很大,对应于一个不断增长的表。

2 个答案:

答案 0 :(得分: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
     )

答案 1 :(得分: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