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

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


Giới thiệu INNER JOIN

INNER JOIN (hoặc JOIN) chỉ trả về các hàng có giá trị khớp nhau ở cả hai bảng dựa trên điều kiện nối. Hàng không khớp sẽ bị loại bỏ.

Cú pháp

SELECT cot1, cot2... FROM bang_1 INNER 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 INNER 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 (Inder có Dept_id=125 không có trong Department):

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

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

INNER 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 INNER 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', 'Physics')

Hàng thứ 4 (Inder) không xuất hiện vì không có bản ghi khớp trong bảng Department.