读书人

简单的SQL查询,该怎么解决

发布时间: 2012-05-12 15:39:31 作者: rapoo

简单的SQL查询
刚才一位同学提到的:

insert into t111 select '张一','000000'
insert into t111 select '张二','1111'
insert into t111 select '张三','222222222'
insert into t222 select '李1','1111'
insert into t222 select '张一','000000'
insert into t222 select '张二','1111'
insert into t222 select '张四','1111'

Select b.[name],b.tel From t111 a , t222 b Where (b.name not in (Select [name] From t111))
Select distinct b.[name],b.tel From t111 a , t222 b Where (b.name not in (Select [name] From t111))

为何第一个查询返回6条结果:
李11111
李11111
李11111
张四1111
张四1111
张四1111
第二个查询结果才是想要的:
李11111
张四1111

求解


[解决办法]
原因出在这句话上:“From t111 a , t222 b”
这句话会对t111和t222做笛卡尔积,产生一个大表,在这个表中,原t222的每条记录都会重复出现3次(为什么是3次?因为t111的总记录数为3),select的时候是select这个大表,所以会出现重复3次的记录,需要用distinct对重复值进行消除。

读书人网 >SQL Server

热点推荐