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

Đếm chuỗi giống nhau trong cột MySQL mới?

Sử dụng COUNT() 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.53 sec)

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

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)

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 |
+------------------+
| Larry            |
| John             |
| Larry            |
| David            |
| Bob              |
| Larry            |
| David            |
| Larry            |
+------------------+
8 rows in set (0.00 sec)

Truy vấn sau để đếm các chuỗi giống nhau trong MySQL:

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

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

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