如何优化为查找表运行的多个子查询

时间:2018-01-01 15:18:22

标签: sql oracle

我有两个looK up表,需要通过关联两个表来获取值。

截至目前,我正在使用多个子查询并尝试找到最简单的方法。

 SELECT
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'A') AND T1.ID = 'AA')as A,
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'B') AND T1.ID = 'BB')AS B,
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'C') AND T1.ID = 'CC')AS C,
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'D') AND T1.ID = 'DD')AS D,
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'E') AND T1.ID = 'EE')AS E,
  (SELECT TYPE_NAME FROM T1 where FK_T2 = (SELECT  PK FROM  T2 WHERE  T2.ID = 'F') AND T1.ID = 'FF')AS F
   FROM MYTABLE;

3 个答案:

答案 0 :(得分:2)

我会尝试类似的事情:

SELECT
    T1.TYPE_NAME,
    T1.ID
FROM T1 t1
INNER JOIN T2 t2
    ON t1.FK_T2 = t2.PK
WHERE
    T1.ID||T1.ID = T2.ID

答案 1 :(得分:2)

我认为你需要这样的东西。

   SELECT  MAX ( CASE WHEN T1.ID = 'AA' AND T2.ID = 'A' THEN TYPE_NAME  END ) as A,
           MAX ( CASE WHEN T1.ID = 'BB' AND T2.ID = 'B' THEN TYPE_NAME  END ) as B,
           MAX ( CASE WHEN T1.ID = 'CC' AND T2.ID = 'C' THEN TYPE_NAME  END ) as C,
           ..

    FROM T1 t1
    INNER JOIN T2 t2
        ON t1.FK_T2 = t2.PK

答案 2 :(得分:1)

您可以尝试将这些查询重新表述为由两个表之间的连接组成的单个查询:

SELECT
    T1.TYPE_NAME,
    T1.ID
FROM T1 t1
INNER JOIN T2 t2
    ON t1.FK_T2 = t2.PK
WHERE
    (T1.ID = 'AA' AND T2.ID = 'A') OR
    (T1.ID = 'BB' AND T2.ID = 'B') OR
    (T1.ID = 'CC' AND T2.ID = 'C') OR
    (T1.ID = 'DD' AND T2.ID = 'D') OR
    (T1.ID = 'EE' AND T2.ID = 'E') OR
    (T1.ID = 'FF' AND T2.ID = 'F');

通过检查第一个表中ID列的值,可以跟踪每个返回记录对应的子查询。这将作为源子查询的标记。