sqlserver里面使用in查询与表join查询的区别
发布时间:2020-12-12 13:10:18 所属栏目:MsSql教程 来源:网络整理
导读:我们先建一个张表: 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里面
我们先建一个张表: CREATE TABLE Test_table ( id INT,age INT NOT NULL ) 造一些数据: insert Test_table values (1,18),(2,28),(3,25) 来看看表里面的数据: id ?age ? 我们来看看通过in去查询数据(注意,in里面的条件我故意重复): select * from Test_table where id in (1,1,1) 但是查询出来的数据,只有一条! id ?age ? 如果我新建一个临时表,然后往临时表里面插入冗余的记录,最后和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 ? 如果我继续使用in去访问#Temp临时表的数据: select t.* from Test_table t where t.id in( select temp.id from #Temp temp ) 查询结果也是去重的,只有一条: id ?age ? 所以,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语法都可以去掉重复的数据。其优缺点大家可以再研究吧。。。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 实例解析MySQL中的存储过程及存储过程的调用方法
- sql – 在数据库中存储可重新排序的项目的高效方法
- SqlServer 执行计划+IO统计信息
- sql-server – 具有许多并发,长时间运行的查询的SQL Server
- sql – INSTEAD OF触发器和CASCADE路径
- sql-server-2008 – VS 2010构建数据库项目接收SQL04151
- sql-server – Hibernate返回一个新插入的行的auto-generat
- sql-server – SQL Server差异(与交叉相反)
- sql – 你会使用一个或两个表的用户名和密码?
- Redis上实现分布式锁以提高性能的方案研究