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

ใช้ LEFT JOIN จำลอง MINUS Query ใน MySQL

MySQL ไม่มี MINUS/EXCEPT ใช้ LEFT JOIN แทน

หาข้อมูลที่อยู่ในตารางหนึ่งแต่ไม่อยู่ในอีกตารางหนึ่ง

ข้อมูลตัวอย่าง

Student_detail (7 แถว)

+-----------+---------+------------+------------+
| studentid | Name    | Address    | Subject    |
+-----------+---------+------------+------------+
| 101       | YashPal | Amritsar   | History    |
| 105       | Gaurav  | Chandigarh | Literature |
| 130       | Ram     | Jhansi     | Computers  |
| 132       | Shyam   | Chandigarh | Economics  |
| 133       | Mohan   | Delhi      | Computers  |
| 150       | Rajesh  | Jaipur     | Yoga       |
| 160       | Pradeep | Kochi      | Hindi      |
+-----------+---------+------------+------------+

Student_info (6 แถว)

+-----------+-----------+------------+-------------+
| studentid | Name      | Address    | Subject     |
+-----------+-----------+------------+-------------+
| 101       | YashPal   | Amritsar   | History     |
| 105       | Gaurav    | Chandigarh | Literature  |
| 130       | Ram       | Jhansi     | Computers   |
| 132       | Shyam     | Chandigarh | Economics   |
| 133       | Mohan     | Delhi      | Computers   |
| 165       | Abhimanyu | Calcutta   | Electronics |
+-----------+-----------+-------------+-------------+

หา studentid ที่อยู่ใน Student_info แต่ไม่อยู่ใน Student_detail

SELECT studentid 
FROM student_info 
LEFT JOIN Student_detail USING(studentid) 
WHERE student_detail.studentid IS NULL;
+-----------+
| studentid |
+-----------+
| 165       |
+-----------+

หา studentid ที่อยู่ใน Student_detail แต่ไม่อยู่ใน Student_info

SELECT studentid 
FROM student_detail 
LEFT JOIN Student_info USING(studentid) 
WHERE student_info.studentid IS NULL;
+-----------+
| studentid |
+-----------+
| 150       |
| 160       |
+-----------+

หลักการ

  • LEFT JOIN เก็บฝั่งซ้ายไว้ทั้งหมด
  • WHERE ... IS NULL กรองเฉพาะที่ไม่มีคู่ในฝั่งขวา
  • เทียบเท่า SELECT ... FROM A MINUS SELECT ... FROM B