Sql查询问题,很奇怪的
如题,三个Sum、Child、Dif表,数据结构相同,表内容分别如下:
Sum:
IDNameSex
IDNameSex
363A男
364B女
365C女
366D女
367B女
370C女
372G女
Child:
IDNameSex
363A女
364B女
365C女
366D男
367E女
Dif为空,
目的:想将child中与A重复的B、C找出,语句如下:
INSERT INTO dbo.dif
(name, sex)
SELECT dbo.Child.Name, dbo.Child.Sex
FROM dbo.Child INNER JOIN
dbo.[Sum] ON dbo.Child.Name = dbo.[Sum].Name AND dbo.Child.Sex = dbo.[Sum].Sex
结果如下:
DIf:
IDNameSex
435B女
436C女
437B女
438C女
为什么找了两次,如何只找一次
[解决办法]
INSERT INTO dbo.dif (name, sex)
SELECT a.Name, a.Sex
FROM dbo.Child as a
Where exists(Select * from dbo.Child
where Name=a.Name and sex=a.sex and id <a.id)
[解决办法]
declare @Sum table(ID varchar(255),Name varchar(255),Sex varchar(255))
insert @Sum
select '363 ', 'A ', '男 ' union all
select '364 ', 'B ', '女 ' union all
select '365 ', 'C ', '女 ' union all
select '366 ', 'D ', '女 ' union all
select '367 ', 'B ', '女 ' union all
select '370 ', 'C ', '女 ' union all
select '372 ', 'G ', '女 '
declare @Child table(ID varchar(255),Name varchar(255),Sex varchar(255))
insert @Child
select '363 ', 'A ', '女 ' union all
select '364 ', 'B ', '女 ' union all
select '365 ', 'C ', '女 ' union all
select '366 ', 'D ', '男 ' union all
select '367 ', 'E ', '女 '
declare @Dif table(ID varchar(255),Name varchar(255),Sex varchar(255))
insert into @Dif
select distinct a.*
from @Child a join @Sum b
on a.Name = b.Name and a.Sex = b.Sex
select * from @Dif
/*
IDNameSex
364B女
365C女
*/