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

วิธีทำ Self Join บนตารางใน MySQL ด้วย Python


สามารถ JOIN ตารางสองตารางใน SQL ได้จากคอลัมน์ร่วมหรือเงื่อนไขที่ระบุ มีหลายประเภทของ JOIN

ที่นี่จะพูดถึง SELF JOIN ซึ่งเป็นการ JOIN ตารางกับตัวมันเอง ทำระหว่างสองสำเนาของตารางเดียวกัน แถวของตารางจะถูกจับคู่กับแถวอื่นของตารางเดียวกันตามเงื่อนไข

ไวยากรณ์

SELECT a.column1, b.column2 FROM table_name a, table_name b WHERE condition;
  • a และ b คือ alias ของตารางเดียวกัน
  • table_name ใช้ซ้ำสองครั้งเพราะเป็น self join

ตาราง Students:

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

Self join ตามเงื่อนไข a.Dept_id < b.Dept_id หมายถึงแต่ละแถวจะจับคู่กับแถวอื่นที่ Dept_id น้อยกว่า

ขั้นตอนทำ Self Join ด้วย MySQL ใน Python

  • นำเข้า MySQL Connector

  • สร้างการเชื่อมต่อด้วย connect()

  • สร้างออบเจ็กต์ cursor ด้วย cursor()

  • สร้างคำสั่ง SQL ที่เหมาะสม

  • รันคำสั่งด้วย execute()

  • ปิดการเชื่อมต่อ

ตัวอย่าง

import mysql.connector
db = mysql.connector.connect(
    host="your_host",
    user="your_username",
    password="your_password",
    database="database_name"
)
cursor = db.cursor()
query = "SELECT a.Dept_id, b.Student_name FROM Students a, Students b WHERE a.Dept_id < b.Dept_id"
cursor.execute(query)
rows = cursor.fetchall()
for x in rows:
    print(x)
db.close()

ผลลัพธ์

Dept_idStudent_name
120Rohit
120Kirat
120Inder
121Inder
121Inder