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

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


Giới thiệu FULL JOIN

FULL JOIN trả về tất cả bản ghi từ cả hai bảng. Đối với bản ghi không khớp, giá trị NULL sẽ được chèn vào bên tương ứng.

Cú pháp

SELECT cot1, cot2... FROM bang_1 FULL 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 FULL 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:

Students:
+----------+--------------+-----------+
| id       | Student_name | Dept_id   |
+----------+--------------+-----------+
| 1        | Rahul        | 120       |
| 2        | Rohit        | 121       |
| 3        | Kirat        | 121       |
| 4        | Inder        | 123       |
+----------+--------------+-----------+

Department:
+----------+-----------------+
| Dept_id  | Department_name |
+----------+-----------------+
| 120      | CSE             |
| 121      | Mathematics     |
| 122      | Physics         |
+----------+-----------------+

FULL JOIN trên cột Dept_id chung:

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

Kết quả

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

Tất cả bản ghi từ cả hai bảng đều được bao gồm, kể cả khi không có bản ghi khớp.