连接两个选择查询,其中第一个查询的值用于第二个选择查询

时间:2015-01-08 00:34:33

标签: sql oracle oracle11g

如何连接两个select语句,其中第一个select语句的结果用于第二个select语句

实施例: 查询1

SELECT C.columnDescription, A.accounnumber, C.AcroColumn   
  FROM table_1 A JOIN table_2 B ON NVL(A.column1, A.column2) = B.column1, table_3 C 
 WHERE A.column4 = 'Apple' AND C.column1 = 'Apple' AND A.column6 = C.column2 AND  B.column2 = '00'
   AND C.column9 = 'N' AND (B.column5 = 'K' OR B.column8 = 'T')  ORDER BY A.column6;

查询2

Select column_2, column_3 from **table_4** where **column_4 from table_4 = accounnumber which we get from table_1

我们从之前的选择查询中得到的。

否则

SELECT C.columnDescription, A.accounnumber, C.AcroColumn   
  FROM table_1 A JOIN table_2 B ON NVL(A.column1, A.column2) = B.column1, table_3 C , table_4 D
 WHERE (D.column_2,D.column_3 in (select A.accounnumber FROM table_1 A JOIN table_2 B
    ON NVL(A.column1, A.column2) = B.column1 )
  A.column4 = 'Apple' AND C.column1 = 'Apple' AND A.column6 = C.column2 AND  B.column2 = '00'
   AND C.column9 = 'N' AND (B.column5 = 'K' OR B.column8 = 'T')  ORDER BY A.column6;

永远执行查询

2 个答案:

答案 0 :(得分:0)

也许这就是你想要的:

Select column_2, column_3
from table_2
where column_4 in (Select column_1 from table_1);

如果您的问题是重复的行,那么这将解决该问题。

编辑:

更高效的版本是:

Select column_2, column_3
from table_2
where exists (Select column_1 from table_1 where table_1.column_1 = table_2.column4);

您应该在table_1(column_1)上有一个索引:

create index idx_table1_column1 on table_1(column_1);

答案 1 :(得分:0)

或者您可以尝试嵌套连接

select column_2, column_3 from table_2 t2
join (select column_1, column_2 from table_1) t1 on t1.column_2 = t2.column_2

也许您应该尝试将查询转换为视图并在查询中替换视图中的表?