如何在Python中使用MySQL执行两个表的右连接?
我们可以基于它们之间的一个公共列或基于某些指定条件在SQL中连接两个表。有不同类型的JOIN可用于连接两个SQL表。
在这里,我们将讨论两个表的RIGHT join。在RIGHT JOIN中,始终在结果中包括第二个表或右表中的所有记录。从左表中,将匹配的记录连接到右表记录中。如果在右表的行中没有找到匹配记录,则将 None 与该记录连接。
两个表根据某些条件连接。但是,右表的所有记录将始终包括在结果中,无论条件如何。
更多Python相关文章,请阅读:Python 教程
语法
SELECT column1, column2...
FROM table_1
RIGHT 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中执行两个表的右连接的步骤
- import MySQL connector
-
使用 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 RIGHT 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’ , ‘Mathematics’)
(None, ‘Physics’)
请注意,即使对于最后一行没有匹配记录,右表中的所有记录也包括在结果中。
极客教程