สามารถ JOIN สองตารางใน SQL ได้จากคอลัมน์ร่วมหรือเงื่อนไขที่ระบุ มีหลายประเภทของ JOIN
ที่นี่จะพูดถึง LEFT JOIN ซึ่งรวมเรคคอร์ดทั้งหมดจากตารางแรก (ตารางซ้าย) ในผลลัพธ์เสมอ จากตารางขวา จะจับคู่เฉพาะเรคคอร์ดที่ตรงเงื่อนไข หากไม่มีการจับคู่ จะใส่ None
ไวยากรณ์
SELECT column1, column2... FROM table_1 LEFT JOIN table_2 ON condition;
ตาราง Students และ Department:
+----------+--------------+-----------+ | id | Student_name | Dept_id | +----------+--------------+-----------+ | 1 | Rahul | 120 | | 2 | Rohit | 121 | | 3 | Kirat | 125 | | 4 | Inder | 123 | +----------+--------------+-----------+
+----------+-----------------+ | Dept_id | Department_name | +----------+-----------------+ | 120 | CSE | | 121 | Mathematics | | 122 | Physics | +----------+-----------------+
Left join ตาม dept_id ที่เหมือนกัน
ขั้นตอนทำ Left Join ด้วย MySQL ใน Python
นำเข้า MySQL Connector
สร้างการเชื่อมต่อด้วย
connect()สร้างออบเจ็กต์ cursor ด้วย
cursor()สร้างคำสั่ง SQL ที่เหมาะสม
รันคำสั่งด้วย
execute()ปิดการเชื่อมต่อ
ตัวอย่าง
import mysql.connector
db = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="database_name"
)
cursor = db.cursor()
query = "SELECT Students.Id, Students.Student_name, Department.Department_name FROM Students LEFT JOIN Department ON Students.Dept_Id = Department.Dept_Id"
cursor.execute(query)
rows = cursor.fetchall()
for x in rows:
print(x)
db.close()ผลลัพธ์
(1, 'Rahul', 'CSE') (2, 'Rohit', 'Mathematics') (3, 'Kirat', None) (4, 'Inder', None)
สังเกตว่าเรคคอร์ดทั้งหมดจากตารางซ้าย (Students) ถูกรวมอยู่ แม้ 2 แถวสุดท้ายจะไม่มีการจับคู่