Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thực hiện RIGHT JOIN trên hai bảng MySQL bằng Python


Giới thiệu RIGHT JOIN

RIGHT JOIN trả về tất cả bản ghi từ bảng bên phải (bảng thứ hai). Các bản ghi khớp từ bảng bên trái được nối thêm. Nếu không khớp, giá trị NULL sẽ xuất hiện ở bên trái.

Cú pháp

SELECT cot1, cot2... FROM bang_1 RIGHT JOIN bang_2 ON dieu_kien;

Các bước thực hiện

  1. Import mysql.connector
  2. Thiết lập kết nối bằng connect()
  3. Tạo đối tượng con trỏ qua cursor()
  4. Viết truy vấn RIGHT JOIN
  5. Thực thi truy vấn bằng execute()
  6. Đóng kết nối

Ví dụ minh họa

Hai bảng Students và Department (giống ví dụ FULL JOIN).

RIGHT JOIN trên Dept_id:

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()

Kết quả

(1, 'Rahul', 'CSE')
(2, 'Rohit', 'Mathematics')
(3, 'Kirat', 'Mathematics')
(None, 'Physics')

Tất cả bản ghi từ bảng bên phải (Department) đều xuất hiện, kể cả hàng không khớp (Physics).