如何在 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 查询

  • 关闭连接

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例

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 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告