使用一个查询而不是两个查询

时间:2017-07-11 08:36:29

标签: sql oracle oracle-sqldeveloper

我有一个像样本一样的查询。查询中有重复,我想最小化它。我怎样才能做到这一点?对不起,如果这是一个非常简单的问题。我是数据库和SQL领域的新手。

SELECT * 
FROM Table1 
WHERE column1 IN (SELECT DISTINCT column1 
                  FROM Table2 
                  WHERE column2 = (SELECT column2 
                                   FROM Table4 
                                   WHERE column3='1324654') 
                  UNION 
                  SELECT DISTINCT column1 
                  FROM Table3 
                  WHERE column2 = (SELECT column2 
                                   FROM Table4 
                                   WHERE column3='1324654'));

子查询中的重复:

SELECT column2 
FROM Table4 
WHERE column3='1324654' 

4 个答案:

答案 0 :(得分:1)

@ugur,你可以使用PL / SQL并创建一个变量,正如@st所建议的那样,但是,如果你关注性能,你也可以只使用SQL,并像现在一样离开:重复的子查询是确定性的,很可能会被缓存,不会造成性能损失。

答案 1 :(得分:1)

如果您只想删除重复

SELECT *
FROM table1
WHERE column1 IN
    ( WITH data AS
    (SELECT column2
    FROM table4
    WHERE column3 = '12324654'
    )
SELECT distint column1
FROM table2,
    data
WHERE table2.column2 = data.column2
UNION
SELECT distinct column1
FROM table3,
    data
WHERE table4.column2 = data.column2
    );

答案 2 :(得分:0)

您可以声明一个变量,该变量将保留重复查询的结果。 像这样:

declare @result varchar=(SELECT column2 FROM Table4 WHERE column3='1324654')

然后在查询中使用它:

SELECT * FROM Table1 WHERE column1 IN 
(SELECT DISTINCT column1 FROM Table2 WHERE 
column2=@result 
UNION 
SELECT DISTINCT column1 FROM Table3 WHERE 
column2=@result);

答案 3 :(得分:0)

您还可以使用with子句:

select *
  from table1
 where column1 in (with tab_helper as 
                   (select column2
                      from table4
                     where column3 = '1324654') 
                     select distinct column1
                       from table2,
                             tab_helper
                      where column2 = tab_helper.column2 
                      union 
                      select distinct column1 
                       from table3,
                            tab_helper 
                     where column2 = tab_helper.column2);