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

วิธีทำ Right Join บนสองตารางใน MySQL ด้วย Python


สามารถ JOIN สองตารางใน SQL ได้จากคอลัมน์ร่วมหรือเงื่อนไขที่ระบุ มีหลายประเภทของ JOIN

ที่นี่จะพูดถึง RIGHT JOIN ซึ่งรวมเรคคอร์ดทั้งหมดจากตารางที่สอง (ตารางขวา) ในผลลัพธ์เสมอ จากตารางซ้าย จะจับคู่เฉพาะเรคคอร์ดที่ตรงเงื่อนไข หากไม่มีการจับคู่ จะใส่ None

ไวยากรณ์

SELECT column1, column2... FROM table_1 RIGHT JOIN table_2 ON condition;

ตาราง Students และ Department เหมือนเดิม

ขั้นตอนทำ Right 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 RIGHT 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')
(None, 'Physics')

สังเกตว่าเรคคอร์ดทั้งหมดจากตารางขวา (Department) ถูกรวมอยู่ แม้แถวสุดท้ายจะไม่มีการจับคู่