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


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

在這裡,我們將討論兩個表的 FULL 連線。在 FULL JOIN 中,兩個表中的所有記錄都包含在結果中。對於找不到匹配記錄的記錄,會在任一側插入 NULL。

語法

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

假設有兩個表,“Students” 和 “Department”,如下所示:

學生表

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

部門表

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

我們將根據 dept_id 對上述兩個表執行全連線,dept_id 是兩個表中都存在的公共列。

在 Python 中使用 MySQL 對兩個表執行全連線的步驟

  • 匯入 MySQL 聯結器

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

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

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

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

  • 關閉連線

示例

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="yourpassword",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()

輸出

(1, ‘Rahul’, ‘CSE’)
(2, ‘Rohit’, ‘Mathematics’)
(3, ‘Kirat’, ‘Mathenatics’)
(4, ‘Inder’, None)
(None, ‘Physics’)

注意,即使某些記錄沒有匹配記錄,兩個表中的所有記錄都包含在結果中。

更新於: 2021年6月10日

254 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.