Sử dụng bảng stock_item nơi cột quantity có giá trị trùng: 'Notebooks' và 'Pencil' đều có quantity = 40.
mysql> Select * from stock_item; +------------+---------+ | item_name | quantity | +------------+---------+ | Calculator | 89 | | Notebooks | 40 | | Pencil | 40 | | Pens | 32 | | Shirts | 29 | | Shoes | 29 | | Trousers | 29 | +------------+---------+ 7 rows in set (0.00 sec)
Truy vấn sau tìm giá trị trùng lặp kèm tên mặt hàng:
mysql> Select distinct g.item_name, g.quantity from stock_item g
INNER JOIN Stock_item b ON g.quantity = b.quantity
WHERE g.item_name <> b.item_name;
+-----------+----------+
| item_name | quantity |
+-----------+----------+
| Pencil | 40 |
| Notebooks | 40 |
| Shoes | 29 |
| Trousers | 29 |
| Shirts | 29 |
+-----------+----------+
5 rows in set (0.00 sec)
Giải thích:
- Tự kết nối (self-join) bảng với alias
gvàb - Điều kiện join:
g.quantity = b.quantity(cùng quantity) - Điều kiện lọc:
g.item_name <> b.item_name(khác tên mặt hàng) DISTINCTloại bỏ hàng trùng lặp trong kết quả