MySQL中count(distinct?col...)組合使用的注意要點詳解
第一步:數據準備
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...)組合使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決mysql錯誤:Subquery?returns?more?than?1?row問題
這篇文章主要介紹了解決mysql錯誤:Subquery?returns?more?than?1?row問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05阿里云ECS centos6.8下安裝配置MySql5.7的教程
阿里云默認yum命令下的MySQL是5.17****,安裝mysql5.7之前先卸載以前的版本。下面通過本文給大家介紹阿里云ECS centos6.8下安裝配置MySql5.7的教程,需要的的朋友參考下吧2017-07-07Mysql8創(chuàng)建用戶及賦權操作實戰(zhàn)記錄
一般在開發(fā)中,我們需要新建一個賬戶,并賦予某個數據庫的訪問權限,下面這篇文章主要給大家介紹了關于Mysql8創(chuàng)建用戶及賦權操作的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-04-04MySQL報錯1040'Too?many?connections'的原因以及解決方案
這篇文章主要給大家介紹了關于MySQL報錯1040'Too?many?connections'的原因以及解決方案,文中通過實例代碼以及圖文介紹的非常詳細,需要的朋友可以參考下2022-07-07mysql臨時表(temporary?table)使用方法詳解
MySQL臨時表在很多場景中都會用到,MySQL內部在執(zhí)行復雜SQL時,需要借助臨時表進行分組、排序、去重等操作,下面這篇文章主要給大家介紹了關于mysql臨時表(temporary?table)使用方法的相關資料,需要的朋友可以參考下2024-01-01