2015-09-07 32 views
0

我正在使用聯合運算符合並2個查詢的結果。現在我想在第二個查詢中使用第一個查詢的結果,這樣我就可以從第二個查詢中排除一些記錄。在較低查詢中使用union子句中的上部查詢的結果

E.g.

select <some_columns> from tableA Union select <same_columns> from tableA where <one_column_val> != <some_val_from_first_query> 

下面是我的查詢

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} 

請建議所需的改變。

在此先感謝

回答

0

每個選擇在SQL工會有沒有其他的知識。所以,你只需要再次明確地寫出整個查詢,在你的情況下可以是NOT EXISTS或NOT IN。如果您的RDBMS支持的CTE你查詢到的CTE可以抽象,而不是重複自己

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 
    ) 

:舉個例子,你可以看到複製爲一個不派生表整個查詢EXISTS子句。注意,如果你的RDBMS支持它,你應該也可以使用JOIN語法,並且你可能會遇到需要解決的*選擇器的列名衝突。

相關問題