สามารถ JOIN สองตารางใน SQL ได้จากคอลัมน์ร่วมหรือเงื่อนไขที่ระบุ มีหลายประเภทของ JOIN
ที่นี่จะพูดถึง FULL JOIN ซึ่งรวมเรคคอร์ดทั้งหมดจากทั้งสองตารางในผลลัพธ์ สำหรับเรคคอร์ดที่ไม่มีการจับคู่ จะใส่ NULL ด้านที่ไม่มีข้อมูล
ไวยากรณ์
SELECT column1, column2... FROM table_1 FULL JOIN table_2 ON condition;
ตาราง Students และ Department:
+----------+--------------+-----------+ | id | Student_name | Dept_id | +----------+--------------+-----------+ | 1 | Rahul | 120 | | 2 | Rohit | 121 | | 3 | Kirat | 121 | | 4 | Inder | 123 | +----------+--------------+-----------+
+----------+-----------------+ | Dept_id | Department_name | +----------+-----------------+ | 120 | CSE | | 121 | Mathematics | | 122 | Physics | +----------+-----------------+
Full join ตาม dept_id ที่เหมือนกันในทั้งสองตาราง
ขั้นตอนทำ Full 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 FULL 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', 'Mathematics') (4, 'Inder', None) (None, 'Physics')
สังเกตว่าเรคคอร์ดทั้งหมดจากทั้งสองตารางถูกรวมอยู่ในผลลัพธ์ แม้จะไม่มีการจับคู่สำหรับบางเรคคอร์ด