当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL中的DISTINCT简介、SQL DISTINCT详解 附DISTINCT的用法、DISTINCT注意事项

SQL中的DISTINCT简介、SQL DISTINCT详解 附DISTINCT的用法、DISTINCT注意事项

2025年05月30日 MsSqlserver 我要评论
distinct简介:distinct 是 sql 中用来返回唯一不重复结果集的关键字。它通常用于 select 语句中,可以指定一个或多个列进行去重,并返回唯一的结果。当你在使用 select 查询

distinct简介:

distinct 是 sql 中用来返回唯一不重复结果集的关键字。它通常用于 select 语句中,可以指定一个或多个列进行去重,并返回唯一的结果。当你在使用 select 查询数据时,可能会得到包含重复行的结果集。为了去除这些重复行,你可以使用 distinct 关键字来获取唯一的记录。

表中插入的原始数据:

1、单列去重:单列去重:使用 distinct 去重查询结果中的单个列,返回唯一的值。

select	distinct age from students

2、多列去重:使用 distinct 去重查询结果中的多个列,返回满足多列组合唯一的结果。

selectdistinct name,age,score from students

3、结合其他关键字:distinct 可以与其他 sql 关键字结合使用,如 order by、where 和 group by 等

select	distinct name,age,score from students order by score desc
select	distinct name ,age,score from students group by name

4、对表达式进行去重:distinct 还可以用于对表达式进行去重,而不仅仅是列名。这允许你根据某些计算得到的结果进行去重。

select distinct ( `name` + age) result from students

5、count()统计

select count(distinct name) num from students

注意事项:

1、distinct 必须放在字段的开头,即放在第一个参数的位置。

2、只能在select语句中使用,不能在insert、delete、update中使用。

3、distinct表示对后面的所有参数的拼接 取 不重复的记录。

4、distinct 忽略 null 值:distinct 关键字默认会忽略 null 值,即将 null 视为相同的值。如果你希望包括 null 值在去重结果中,可以使用 is null 或 is not null 进行过滤。

5、distinct 基于所有选择的列:distinct 关键字基于选择的所有列来进行去重。如果你只想根据部分列进行去重,可以使用子查询或者窗口函数等技术来实现。

6、distinct 的性能消耗:distinct 操作可能会对查询的性能产生一定的影响,特别是在处理大量数据时。因为它需要对结果集进行排序和比较以去除重复行。如果性能是一个关键问题,可以考虑其他优化方法,例如使用索引或者合理设计查询。

7、结果集顺序不保证:使用 distinct 关键字后,结果集的顺序可能会发生变化,因为数据库系统通常会对结果进行重新排列以去除重复行。如果需要特定的结果排序,可以使用 order by 子句进行排序。

完整版代码

create table students (
    id int auto_increment primary key,
    name varchar(50),
    age int,
    score decimal(5, 2)
);
insert into students (name, age, score) values
('alice', 20, 85.5),
('bob', 22, 76.3),
('charlie', 21, 92.0),
('alice', 20, 85.5),
('david', 23, 68.9);
# 原始数据
select	* from students
# 单列去重:使用 distinct 去重查询结果中的单个列,返回唯一的值。
select	distinct age from students
# 多列去重:使用 distinct 去重查询结果中的多个列,返回满足多列组合唯一的结果。
select	distinct name,age,score from students
# 结合其他关键字:distinct 可以与其他 sql 关键字结合使用,如 order by、where 和 group by 等
select	distinct name,age,score from students order by score desc
select	distinct name ,age,score from students group by name
# 对表达式进行去重:distinct 还可以用于对表达式进行去重,而不仅仅是列名。这允许你根据某些计算得到的结果进行去重。
select distinct ( `name` + age) result from students
# count()统计
select count(distinct name) num from students

到此这篇关于sql中的distinct简介、sql distinct详解 附distinct的用法、distinct注意事项的文章就介绍到这了,更多相关sql distinct用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com