MySQL DISTINCT 和計數?


你需要在 MySQL 中將 GROUP BY 命令和聚合函式 count(*) 結合使用才能實現此操作。語法如下

SELECT yourColumnName,COUNT(*) AS anyVariableNameFROM yourTableName GROUP BY yourColumnName;

為了理解以上語法,我們先建立一個表。建立表的查詢如下

mysql> create table selectDistinct_CountDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> AppearanceId int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.63 sec)

使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('Larry',1);
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('John',2);
Query OK, 1 row affected (0.24 sec)
mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('Larry',3);
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('Larry',10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('Carol',11);
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectDistinct_CountDemo(Name,AppearanceId) values('Larry',15);
Query OK, 1 row affected (0.18 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下

mysql> select *from selectDistinct_CountDemo;

輸出如下

+----+-------+--------------+
| Id | Name  | AppearanceId |
+----+-------+--------------+
|  1 | Larry |            1 |
|  2 | John  |            2 |
|  3 | Larry |            3 |
|  4 | Larry |           10 |
|  5 | Carol |           11 |
|  6 | Larry |           15 |
+----+-------+--------------+
6 rows in set (0.00 sec)

以下是用於選擇 DISTINCT 和計數的查詢

mysql> select Name,count(*) as TotalAppearance from selectDistinct_CountDemo
   -> group by Name;

輸出如下

+-------+-----------------+
| Name  | TotalAppearance |
+-------+-----------------+
| Larry |               4 |
| John  |               1 |
| Carol |               1 |
+-------+-----------------+
3 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

519 次瀏覽

啟動你的 職業

完成課程,獲取認證

開始
廣告
© . All rights reserved.