当前位置: 代码网 > it编程>数据库>Mysql > MySQL中count(distinct col...)组合使用的注意要点详解

MySQL中count(distinct col...)组合使用的注意要点详解

2024年08月09日 Mysql 我要评论
第一步:数据准备mysql> select * from my_student;+----+------------+-----------+--------+--------+| id | n

第一步:数据准备

mysql> select * from my_student;
+----+------------+-----------+--------+--------+
| id | number     | name      | sex    | addr   |
+----+------------+-----------+--------+--------+
|  1 | itcast0001 | jim       | female | 北京   |
|  2 | itcast0002 | hanmeimei | female | 上海   |
|  3 | itcast0003 | kate      | female | null   |
|  4 | itcast0004 | tom       | male   | null   |
|  5 | itcast0005 | lintao    | male   | null   |
|  6 | itcast0006 | 张越      | 女     | null   |
+----+------------+-----------+--------+--------+
6 rows in set (0.00 sec)

第二步:数据验证

1.distinct单字段去重

mysql> select distinct addr from my_student;
+--------+
| addr   |
+--------+
| 北京   |
| 上海   |
| null   |
+--------+
3 rows in set (0.00 sec)

2.count和distinct配合使用

1).count(distinct col) 计算该列除 null 之外的不重复行数。

    mysql> select count(distinct addr) from my_student;							①
	+----------------------+
	| count(distinct addr) |
	+----------------------+
	|                    2 |
	+----------------------+
	1 row in set (0.00 sec)
	
	-- 把上述sql改写成 select count(1) from (select distinct col from ...) a; 
	mysql> select count(1) from (select distinct addr from my_student) a;		②
	+----------+
	| count(1) |
	+----------+
	|        3 |
	+----------+
	1 row in set (0.00 sec)

注意比较①和②的结果,是不同的.

2).count(distinct col1, col2) 如果其中一列全为 null,那么即使另一列有不同的值,也返回为 0。

    mysql> select distinct sex,addr from my_student;
	+--------+--------+
	| sex    | addr   |
	+--------+--------+
	| female | 北京   |
	| female | 上海   |
	| female | null   |
	| male   | null   |
	| 女     | null   |
	+--------+--------+
	5 rows in set (0.00 sec)
	
	mysql> select count(distinct sex,addr) from my_student;                     ③
	+--------------------------+
	| count(distinct sex,addr) |
	+--------------------------+
	|                        2 |
	+--------------------------+
	1 row in set (0.00 sec)

	mysql> select count(1) from (select distinct sex,addr from my_student) a;	④
	+----------+
	| count(1) |
	+----------+
	|        5 |
	+----------+
	1 row in set (0.00 sec)

注意比较③和④的结果,也是不同的.

3.上述同样的操作在oracle数据库验证

1).针对上述1)的场景在oracle数据库中验证后,count(distinct col)也是会计算该列除 null 之外的不重复行数,同mysql一样

2).针对上述2)的场景,count(distinct col1, col2)的写法在oracle数据库中不支持.

总结

到此这篇关于mysql中count(distinct col...)组合使用的注意要点的文章就介绍到这了,更多相关mysql count(distinct col...)组合使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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