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

วิธีหาค่าซ้ำในตาราง MySQL


ใช้ตาราง stock_item คอลัมน์ quantity มีค่าซ้ำคือ 40 (Notebooks, Pencil) และ 29 (Shirts, Shoes, Trousers)

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)

คิวรีหาค่าซ้ำพร้อมชื่อสินค้า:

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)

วิธีทำ: Self-join ตารางกับตัวเอง เปรียบเทียบ quantity เดียวกัน แต่ item_name ต่างกัน ใช้ DISTINCT เพื่อไม่ให้ซ้ำ