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
- Import
mysql.connector - Thiết lập kết nối bằng
connect() - Tạo đối tượng con trỏ qua
cursor() - Viết truy vấn FULL JOIN
- Thực thi truy vấn bằng
execute() - Đó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.