union 和 where 子句

union along with a where clause

我想做这样的事情,但我知道这会导致错误

select * from t1 a
union 
select * from t2 b
union 
select * from t3 c
where b.col1!=c.col1

我应该使用什么来实现上述目标?..

谢谢!!

我想你想要 NOT EXISTS:

select * from t1
union 
select * from t2
union 
select * from t3
where not exists (
  select 1 from t2
  where t2.col1 = t3.col1
)

使用此查询,只有当 col1 的值不存在于 t2 的任何行中时,t3 的行才会包含在最终结果中。

您可以使用 exists :

select a.col1, a.col2, . . .
from t1 a union all
select b.col1, b.col2, . . .
from t2 b union all
select c.col1, c.col2, . . .
from t3 c
where not exists (select 1 from t2 b where c.col1 = b.col1);

注意:在 union all 中使用明确的列名。