如何在 Python 中使用 MySQL 對兩個表執行內連線?


我們可以根據兩個表之間的一個公共列或基於某些指定條件來連線 SQL 中的兩個表。有多種型別的 JOIN 可用於連線兩個 SQL 表。

這裡,我們將討論兩個表的內連線。

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      |
+----------+-----------------+

我們將根據兩個表中都存在的 dept_id 連線以上兩個表。

在 Python 中使用 MySQL 連線兩個表的步驟

  • 匯入 MySQL 聯結器

  • 使用 connect() 方法建立與聯結器的連線

  • 使用 cursor() 方法建立遊標物件

  • 使用適當的 mysql 語句建立查詢

  • 使用 execute() 方法執行 SQL 查詢

  • 關閉連線

示例

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 表中沒有與 Students 表的第 4 行匹配的記錄。

更新於: 2021年6月10日

3K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告