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

หาค่าซ้ำในคอลัมน์ด้วย SELF JOIN ใน MySQL

ใช้ SELF JOIN หาค่า quantity ซ้ำ

JOIN ตารางกับตัวเอง โดยจับคู่คอลัมน์ quantity และกรอง item_name ไม่ซ้ำกัน

ข้อมูล stock_item

+------------+----------+
| item_name  | quantity |
+------------+----------+
| Calculator | 89       |
| Notebooks  | 40       |
| Pencil     | 40       |
| Pens       | 32       |
| Shirts     | 29       |
| Shoes      | 29       |
| Trousers   | 29       |
+------------+----------+

คำสั่ง SQL

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       |
+-----------+----------+

การอธิบาย

  • g และ b เป็น alias ของตารางเดียวกัน
  • JOIN ON quantity เหมือนกัน
  • WHERE item_name <> item_name กันการจับคู่ตัวเอง
  • DISTINCT กรองแถวซ้ำจากการจับคู่สองทิศทาง

วิธีอื่น (Moder MySQL 8.0+)

SELECT item_name, quantity
FROM stock_item
GROUP BY quantity
HAVING COUNT(*) > 1;