如何使用 MySQL 獲取列中特定值的計數?


我們首先建立一個表 -

mysql> create table DemoTable
   (
      Id int,
      Name varchar(100)
   );
Query OK, 0 rows affected (1.40 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values(100,'John');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(102,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(103,'Chris');
Query OK, 1 row affected (1.05 sec)
mysql> insert into DemoTable values(104,'David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(105,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(106,'Carol');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(107,'Bob');
Query OK, 1 row affected (0.18 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+------+-------+
| Id   | Name  |
+------+-------+
| 100  | John  |
| 101  | Chris |
| 102  | Chris |
| 103  | Chris |
| 104  | David |
| 105  | Chris |
| 106  | Carol |
| 107  | Bob   |
+------+-------+
8 rows in set (0.00 sec)

以下是獲取列中特定值計數的查詢,此處為“Chris” -

mysql> select count(*) from DemoTable where Name='Chris';

這將產生以下輸出 -

+----------+
| count(*) |
+----------+
| 4        |
+----------+
1 row in set (0.00 sec)

更新時間: 02-Jul-2020

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
Advertisements
© . All rights reserved.