利用 MySQL 查詢獲取列中不同記錄的計數
要獲取不同記錄的計數,請使用 DISTINCT 連同 COUNT()。以下是語法 −
select count(DISTINCT yourColumnName) from yourTableName;
讓我們首先建立一個表 −
mysql> create table DemoTable -> ( -> Name varchar(20), -> Score int -> ); Query OK, 0 rows affected (0.67 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable values('John',56); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Sam',89); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('John',56); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Carol',60); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('Sam',89); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Carol',60); Query OK, 1 row affected (0.20 sec)
使用 select 語句顯示錶中的所有記錄 −
mysql> select *from DemoTable
輸出
這將產生以下輸出 −
+-------+-------+ | Name | Score | +-------+-------+ | John | 56 | | Sam | 89 | | John | 56 | | Carol | 60 | | Sam | 89 | | Carol | 60 | +-------+-------+ 6 rows in set (0.00 sec)
以下是獲取列中不同記錄計數的查詢 −
mysql> select count(DISTINCT Score) from DemoTable;
輸出
這將產生以下輸出 −
+-----------------------+ | count(DISTINCT Score) | +-----------------------+ | 3 | +-----------------------+ 1 row in set (0.00 sec)
廣告