Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oracle 在下级查询中使用union子句中的上级查询结果_Oracle_Union - Fatal编程技术网

Oracle 在下级查询中使用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,

我使用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,
       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
    )