在新的 MySQL 列中計數相同的字串?


對此使用 COUNT()。讓我們首先建立一個表格 −

mysql> create table DemoTable
   (
   StudentFirstName varchar(20)
   );
Query OK, 0 rows affected (0.53 sec)

使用插入命令在表格中插入記錄 −

mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表格中顯示所有記錄 −

mysql> select * from DemoTable;

這將生成以下輸出 −

+------------------+
| StudentFirstName |
+------------------+
| Larry            |
| John             |
| Larry            |
| David            |
| Bob              |
| Larry            |
| David            |
| Larry            |
+------------------+
8 rows in set (0.00 sec)

以下是用於在 MySQL 中計數相同字串的查詢 −

mysql> select StudentFirstName,concat(count(StudentFirstName),' times') from DemoTable
group by StudentFirstName;

這將生成以下輸出 −

+------------------+------------------------------------------+
| StudentFirstName | concat(count(StudentFirstName),' times') |
+------------------+------------------------------------------+
| Larry            | 4 times                                  |
| John             | 1 times                                  |
| David            | 2 times                                  |
| Bob              | 1 times                                  |
+------------------+------------------------------------------+
4 rows in set (0.00 sec)

更新時間: 30-Jul-2019

92 次檢視

開啟你的 職業

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.