加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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 ?
-- ?--- ?
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语法都可以去掉重复的数据。其优缺点大家可以再研究吧。。。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读