gpt4 book ai didi

sql - VIEW内的Oracle SQL Reuse子查询

转载 作者:行者123 更新时间:2023-12-03 21:38:35 25 4
gpt4 key购买 nike

我正在尝试建立一个可能包含 1000 条记录的 View 。某些字段需要返回完全相同数据的子查询。我想知道我是否可以在 View 中查询一次,而不是每次都运行它。

以下是一些示例表/数据:

DROP VIEW MYVIEW;
DROP TABLE MYTABLE;
DROP TABLE MYTABLE_PARENT;

-- TABLES FOR VIEW
CREATE TABLE MYTABLE_PARENT ( PRIMARY_KEY NUMBER PRIMARY KEY );
CREATE TABLE MYTABLE ( PRIMARY_KEY NUMBER, MYVAL VARCHAR(255), PARENT_PRIMARY_KEY NUMBER);
INSERT INTO MYTABLE_PARENT VALUES (1);
INSERT INTO MYTABLE_PARENT VALUES (2);
INSERT INTO MYTABLE VALUES (1, 'MYVAL1-1', 1);
INSERT INTO MYTABLE VALUES (2, 'MYVAL1-2', 1);
INSERT INTO MYTABLE VALUES (3, 'MYVAL2-1', 2);

-- VIEW
CREATE OR REPLACE FORCE VIEW MYVIEW AS
SELECT CS.PRIMARY_KEY AS PARENT_PK,

-- THE BELOW STATEMENTS REUSE THE SAME INNER SUBQUERY, IF THE
-- VIEW CONTAINS 1000 ROWS, THE INNER SUBQUERY WILL BE EXECUTED
-- 1000 TIMES, RETURNING THE SAME DATA EACH TIME.
(SELECT PRIMARY_KEY FROM MYTABLE WHERE MYVAL = 'MYVAL1-1' AND
PARENT_PRIMARY_KEY = (SELECT PRIMARY_KEY FROM MYTABLE_PARENT
WHERE PRIMARY_KEY = CS.PRIMARY_KEY)) AS OUTPUT_VAL_1,

(SELECT PRIMARY_KEY FROM MYTABLE WHERE MYVAL = 'MYVAL1-2' AND
PARENT_PRIMARY_KEY = (SELECT PRIMARY_KEY FROM MYTABLE_PARENT
WHERE PRIMARY_KEY = CS.PRIMARY_KEY)) AS OUTPUT_VAL_2
-- DEFINE CS
FROM MYTABLE_PARENT CS;

SELECT * FROM MYVIEW;

select语句的结果如下:
PARENT_PK              OUTPUT_VAL_1           OUTPUT_VAL_2           
---------------------- ---------------------- ----------------------
1 1 2
2

因此,在上面的查询中,我只想为 View 中的每一行运行一次以下查询:
(SELECT PRIMARY_KEY FROM MYTABLE_PARENT WHERE PRIMARY_KEY = CS.PRIMARY_KEY)

有没有办法优化 View 中的内部子查询?

最佳答案

对于单个访问 mytable 和 mytable_parent,请尝试:

CREATE OR REPLACE FORCE VIEW MYVIEW AS 
SELECT CS.PRIMARY_KEY AS PARENT_PK,
MAX(DECODE(MT.MYVAL, 'MYVAL1-1',MT.PRIMARY_KEY, TO_NUMBER(NULL))
AS OUTPUT_VAL_1,
MAX(DECODE(MT.MYVAL, 'MYVAL1-2',MT.PRIMARY_KEY, TO_NUMBER(NULL))
AS OUTPUT_VAL_2
FROM MYTABLE_PARENT CS
LEFT JOIN MYTABLE MT ON MT.PARENT_PRIMARY_KEY = CS.PRIMARY_KEY AND
MT.MYVAL IN ('MYVAL1-1', 'MYVAL1-2')
GROUP BY CS.PRIMARY_KEY

关于sql - VIEW内的Oracle SQL Reuse子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com