oracle sql - 优化SELECT多行作为列

时间:2017-04-27 09:03:25

标签: sql oracle query-optimization sql-optimization

这是我的表'扩展',它引用了'master'表。

MASTER_ID TEXT CATEGORY
1          A1   AA
1          A2   BB
1          A3   CC

我需要将这些类别作为我的选择查询中的列,所以我想出了这些查询:

SELECT MASTER_ID,
(SELECT TEXT FROM EXTENSION WHERE CATEGORY = "AA") AS "AATEXT",
(SELECT TEXT FROM EXTENSION WHERE CATEGORY = "BB") AS "BBTEXT",
(SELECT TEXT FROM EXTENSION WHERE CATEGORY = "CC") AS "CCTEXT"

FROM MASTER 
JOIN EXTENSION 
ON MASTER.ID = EXTENSION.MASTER_ID

结果:

MASTER_ID CATEGORY_1 CATEGORY_2 CATEGORY_3
1         AA         BB         CC

它有效,但性能是一个问题。任何想法如何优化?

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以使用pivot语句来实现此目的:

SELECT * FROM EXTENSION
PIVOT (max(CATEGORY) FOR TEXT
  IN ('A1' AS Category_1, 'A2' AS Category_2, 'A3' AS Category_3))

对您的数据执行上述查询会产生以下输出:

MASTER_ID | CATEGORY_1 | CATEGORY_2 | CATEGORY_3
1         | AA         | BB         | CC

这可能比您的查询效果更好。

答案 1 :(得分:-1)

SELECT M.MASTER_ID,
     CASE WHEN E.CATEGORY = 'AA' THEN E.TEXT END AS AATEXT,
     CASE WHEN E.CATEGORY = 'BB' THEN E.TEXT END AS BBTEXT.
     CASE WHEN E.CATEGORY = 'CC' THEN E.TEXT END AS CCTEXT
     FROM MASTER M
     INNER JOIN EXTENSION  E
     ON (M.MASTER.ID = E.EXTENSION.MASTER_ID)

您可以使用此查询