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

การใช้ UNION ใน MySQL ผ่าน Python

UNION ใน MySQL

UNION รวมผลลัพธ์ของ 2 SELECT queries โดยตัด duplicate rows ออก (UNION ALL เก็บ duplicates ไว้)

เงื่อนไข

  • จำนวน columns ต้องเท่ากัน
  • Data types ตรงกัน
  • ลำดับ columns ตรงกัน

ขั้นตอนใช้ UNION ใน Python

  1. import mysql.connector
  2. connect() สร้าง connection
  3. cursor() สร้าง cursor
  4. เขียน query ใช้ UNION
  5. execute() และ fetchall()
  6. ปิด connection

ตัวอย่างตาราง

Students

id | Student_name | Dept_id
1  | Rahul        | 120
2  | Rohit        | 121
3  | Kirat        | 125
4  | Inder        | 123

Department

Dept_id | Department_name
120     | CSE
121     | Mathematics
122     | Physics

ตัวอย่างโค้ด Python

import mysql.connector

db = mysql.connector.connect(
    host="your_host",
    user="your_username",
    password="your_password",
    database="database_name"
)

cursor = db.cursor()
query = "SELECT Dept_id FROM Students UNION SELECT Dept_id FROM Department"
cursor.execute(query)

rows = cursor.fetchall()
for row in rows:
    print(row)

db.close()

ผลลัพธ์

120
121
125
123
122

คำอธิบาย

UNION คืนค่า Dept_id ที่ไม่ซ้ำจากทั้ง 2 ตาราง (120,121,125,123,122) เรียงจากน้อยไปมาก

UNION ALL

ถ้าต้องการเก็บ duplicates ใช้ UNION ALL แทน