Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách đếm cột distinct trong MySQL?

Bạn cần sử dụng GROUP BY cho việc này. Trước hết, hãy tạo một bảng:

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

Chèn các bản ghi vào bảng bằng lệnh insert:

mysql> insert into DemoTable values('John'); Query OK, 1 row affected (1.34 sec)
mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob'); Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable values('Bob'); Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.14 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:

mysql> select * from DemoTable;

Điều này sẽ tạo ra đầu ra sau:

+------------------+
| StudentFirstName |
+------------------+
| John             |
| Carol            |
| John             |
| John             |
| Bob              |
| David            |
| Bob              |
| Carol            |
| Robert           |
+------------------+
9 rows in set (0.00 sec)

Đây là truy vấn để đếm cột distinct trong MySQL:

mysql> select StudentFirstName, count(*) from DemoTable group by StudentFirstName;

Điều này sẽ tạo ra đầu ra sau:

+------------------+----------+
| StudentFirstName | count(*) |
+------------------+----------+
| John             | 3        |
| Carol            | 2        |
| Bob              | 2        |
| David            | 1        |
| Robert           | 1        |
+------------------+----------+
5 rows in set (0.00 sec)