我们先建一个张表:
CREATE table Test_table( ID INT,age INT NOT NulL)
造一些数据:
insert Test_table values (1,18),(2,28),(3,25)
来看看表里面的数据:
ID age
-- ---
1 18
2 28
3 25
我们来看看通过in去查询数据(注意,in里面的条件我故意重复):
select * from Test_table where ID in (1,1,1)
但是查询出来的数据,只有一条!
ID age
-- ---
1 18
如果我新建一个临时表,然后往临时表里面插入冗余的记录,最后和Test_table连接查询来试试:
-- 新建临时表CREATE table #Temp( ID INT -- 只有一列)-- 插入冗余的记录insert #Temp values (1),(1),(1)--join查询select t.* from Test_table t,#Temp temp where t.ID = temp.ID
查询结果,有四条!
ID age
-- ---
1 18
1 18
1 18
1 18
如果我继续使用in去访问#Temp临时表的数据:
select t.* from Test_table t where t.ID in( select temp.ID from #Temp temp )
查询结果也是去重的,只有一条:
ID age
-- ---
1 18
所以,in会自动distinct里面的集合的,
但是表与表之间join查询,则需要手动的去掉重复数据:
select distinct t.* from Test_table t,#Temp temp where t.ID = temp.ID -- 这样可以实现效果(个人不推荐。。。)select t.* from Test_table t where exists (select 1 from #Temp temp where temp.ID = t.ID ) -- 也可以这样select t.* from Test_table t where t.ID = (select ID from #Temp temp group by temp.ID ) --还可以这样
ID age
-- ---
1 18
因此,distinct,group by 和 exists语法都可以去掉重复的数据。其优缺点大家可以再研究吧。。。
@H_404_109@ 总结以上是内存溢出为你收集整理的sqlserver里面使用in查询与表join查询的区别全部内容,希望文章能够帮你解决sqlserver里面使用in查询与表join查询的区别所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)