Use tempdb;
Go
Create table [dbo].[a] (name varchar null);
Create table [dbo].[b] (name varchar null);
Create table [dbo].[c] (name varchar null);
Insert Into [dbo].[a] values ('a'),('b'),('c');
Insert Into [dbo].[b] values ('a'),('d'),('c');
Insert Into [dbo].[c] values ('a'),('e'),('f');
GO
Select name From dbo.a
except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
Union All
Select name From dbo.b
except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
Union All
Select name From dbo.c
except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
明明应该有6条记录,以上代码返回5条记录,把相同name的c记录去掉了,为何呢??
SQL
------解决方案--------------------
不知道为什么,但是用这种可以
with t as
(
Select name From dbo.a except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
),t1 as
(
Select name From dbo.b except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
),t2 as
(
Select name From dbo.c except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
)
select * from t
union all
select * from t1
union all
select * from t2
------解决方案--------------------
原因很简单,union 和 except、 intersect 的优先级是相同的,所以请使用括号:
Select name From dbo.a
except (
Select name From dbo.a
Intersect
Select name From dbo.b
Intersect
Select name From dbo.c
)
Union All (
Select name From dbo.b
except (
Select name From dbo.a
Intersect