Để tìm các hàng trùng lặp (trùng trên nhiều cột) và đếm số lần xuất hiện, dùng GROUP BY nhiều cột kết hợp HAVING COUNT(*) > 1.
Ví dụ minh họa
Tạo bảng:
mysql> create table DemoTable(
Name varchar(100),
Age int
);
Chèn dữ liệu (có trùng lặp Name+Age):
mysql> insert into DemoTable values('Chris',23);
mysql> insert into DemoTable values('David',21);
mysql> insert into DemoTable values('Chris',23);
mysql> insert into DemoTable values('Chris',21);
mysql> insert into DemoTable values('Mike',25);
mysql> insert into DemoTable values('David',21);
Hiển thị dữ liệu:
mysql> select * from DemoTable;
Kết quả:
+-------+------+ | Name | Age | +-------+------+ | Chris | 23 | | David | 21 | | Chris | 23 | | Chris | 21 | | Mike | 25 | | David | 21 | +-------+------+
Truy vấn tìm trùng lặp và đếm
mysql> select Name, Age, count(*) AS Repeated from DemoTable group by Name, Age having Repeated > 1;
Kết quả:
+-------+------+----------+ | Name | Age | Repeated | +-------+------+----------+ | Chris | 23 | 2 | | David | 21 | 2 | +-------+------+----------+
Giải thích:
GROUP BY Name, Age: Nhóm theo cặp (Name, Age) - cả hai phải trùng mới tính là duplicateCOUNT(*): Đếm số hàng trong mỗi nhómHAVING Repeated > 1: Chỉ giữ nhóm xuất hiện ≥ 2 lần- Chris-23: 2 lần, David-21: 2 lần. Chris-21 chỉ 1 lần → không hiển thị
Cách này dùng cho: dọn dẹp dữ liệu trùng, phát hiện lỗi nhập liệu, thống kê tần suất tổ hợp giá trị.