Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

นับจำนวนครั้งที่คำเฉพาะปรากฏในคอลัมน์ MySQL

สำหรับเรื่องนี้ ใช้ฟังก์ชัน COUNT() ครับ

สร้างตารางตัวอย่าง

mysql> create table DemoTable (
    EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    EmployeeName varchar(100)
);
Query OK, 0 rows affected (0.62 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable(EmployeeName) values('John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(EmployeeName) values('David');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(EmployeeName) values('Bob');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(EmployeeName) values('Sam');
Query OK, 1 row affected (0.12 sec)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;

ผลลัพธ์

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 1          | John         |
| 2          | Carol        |
| 3          | David        |
| 4          | Carol        |
| 5          | Carol        |
| 6          | Bob          |
| 7          | Sam          |
+------------+--------------+
7 rows in set (0.00 sec)

คำสั่งนับจำนวนครั้งที่คำ "Carol" ปรากฏ

mysql> select EmployeeName, count(EmployeeId) as Occurrence from DemoTable where EmployeeName = 'Carol';

ผลลัพธ์

+--------------+------------+
| EmployeeName | Occurrence |
+--------------+------------+
| Carol        | 3          |
+--------------+------------+
1 row in set (0.05 sec)

คำอธิบาย: WHERE กรองเฉพาะ 'Carol' COUNT(EmployeeId) นับจำนวนแถว (Primary Key ไม่มี NULL จึงนับได้ถูกต้อง)