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

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


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

ที่นี่จะพูดถึง INNER JOIN ซึ่ง JOIN และ INNER JOIN ทำงานเหมือนกัน INNER JOIN จะจับคู่แต่ละแถวในตารางหนึ่งกับทุกแถวในอีกตาราง และรวมแถวที่มีคอลัมน์ร่วมหรือตรงเงื่อนไขที่ระบุ

ไวยากรณ์

SELECT column1, column2... FROM table_1 INNER JOIN table_2 ON condition;

ตาราง Students และ Department:

+----------+--------------+-----------+
| id       | Student_name | Dept_id   |
+----------+--------------+-----------+
| 1        | Rahul        | 120       |
| 2        | Rohit        | 121       |
| 3        | Kirat        | 122       |
| 4        | Inder        | 125       |
+----------+--------------+-----------+
+----------+-----------------+
| Dept_id  | Department_name |
+----------+-----------------+
| 120      | CSE             |
| 121      | Mathematics     |
| 122      | Physics         |
+----------+-----------------+

Join ตาม dept_id ที่เหมือนกัน

ขั้นตอน 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 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()

ผลลัพธ์

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

สังเกตว่าแถวที่ 4 ไม่ได้รวมในผลลัพธ์ เพราะไม่มีเรคคอร์ดที่ตรงกันในตาราง Department