如何在 Python 中使用 MySQL 对两个表执行正确连接?
我们可以基于两个表之间的公共列或基于某些指定条件在SQL中连接两个表。有不同类型的JOIN可用于连接两个SQL表。
在这里,我们将讨论两个tables.InRIGHTJOIN上的RIGHT连接,来自第二个表或右表的所有记录总是包含在结果中。从左表,匹配的记录连接到右表的记录。如果在右表中没有找到与行匹配的记录,则None与该记录连接。
这些表是根据某些条件连接的。但是无论条件如何,正确表的所有记录都将始终包含在结果中。
语法
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对两个表执行右连接的步骤
导入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 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’)
请注意,即使最后一行没有匹配的记录,右表中的所有记录都包含在结果中。