Oracle 在下级查询中使用union子句中的上级查询结果
我使用union运算符组合两个查询的结果。现在,我想在第二个查询中使用第一个查询的结果,以便从第二个查询中排除一些记录 例如 下面是我的问题Oracle 在下级查询中使用union子句中的上级查询结果,oracle,union,Oracle,Union,我使用union运算符组合两个查询的结果。现在,我想在第二个查询中使用第一个查询的结果,以便从第二个查询中排除一些记录 例如 下面是我的问题 SELECT a.*, b.*, c.* FROM tableA a, tableB b, tableC c where b.field_1 = c.field_1 and a.field_2 = c.field_2 union SELECT a.*, b.*, c.* FROM tableA a,
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_2 = c.field_2
union
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_3=c.field_3
and a.field_2 <> {a.field_2 from upper query}
请建议所需的修改
提前感谢SQL联合中的每个选择都不知道其他选择。因此,您只需再次显式地写出整个查询,在您的情况下,可以是NOT EXISTS或NOT in。例如,您可以在NOT EXISTS子句中看到作为派生表复制的整个查询:
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_2 = c.field_2
union
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_3=c.field_3
and not exists (
select 1
from (
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_2 = c.field_2
) x
where a.field_2 = x.field_2
)
如果您的RDBMS支持CTE,您可以将查询抽象为CTE,而不必重复。注意:如果您的RDBMS支持联接语法,那么您可能还应该使用联接语法,并且您可能需要解决与*选择器的列名冲突
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_2 = c.field_2
union
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_3=c.field_3
and not exists (
select 1
from (
SELECT a.*, b.*, c.*
FROM tableA a,
tableB b,
tableC c
where b.field_1 = c.field_1
and a.field_2 = c.field_2
) x
where a.field_2 = x.field_2
)