如何使用Python中的MySQL对两个表执行完全连接?
我们可以基于它们之间的公共列或基于某个指定的条件在SQL中连接两个表。连接两个SQL表有不同类型的JOIN可用。
在这里,我们将讨论两个表的完全连接。在完全连接中,两个表中的所有记录都包含在结果中。对于找不到匹配的记录,空值被插入到任意一边。
更多Python相关文章,请阅读:Python 教程
语法
SELECT column1, column2...
FROM table_1
FULL JOIN table_2 ON condition;
假设有两个表,“学生”和“系”,如下所示 –
学生
+----------+--------------+-----------+
| 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执行完全连接。
使用Python中的MySQL对两个表执行完全连接的步骤
- 导入MySQL连接器
-
使用connect()连接器建立连接
-
使用cursor()方法创建游标对象
-
使用适当的mysql语句创建查询
-
使用execute()方法执行SQL查询
-
关闭连接
实例
import mysql.connector
db=mysql.connector.connect(host="你的主机地址", user="你的用户名", password="你的密码",database="数据库名")
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’)
注意,在结果中包含两个表中的所有记录,即使某些记录找不到匹配记录也是如此。
极客教程