如何使用MySQL在Python中对两个表执行inner join操作?
我们可以根据它们之间的公共列或基于某些指定条件,在SQL中连接两个表。有不同的JOIN可用于连接两个SQL表。
在这里,我们将讨论两张表的内联。
JOIN和INNER JOIN的工作方式相同。 INNER JOIN将每个表中的每一行与其他表中的每一行进行匹配,并允许组合两个表中的行,这些行具有某些公共列或满足指定的某些条件。
在对两个表应用联接时,我们需要根据表将被联接的条件指定条件。
更多Python相关文章,请阅读:Python 教程
语法
SELECT column1, column2...
FROM table_1
INNER JOIN table_2 ON condition;
假设有两个表,”Students”和”Department”,如下所示-
学生
+----------+--------------+-----------+
| id | Student_name | Dept_id |
+----------+--------------+-----------+
| 1 | Rahul | 120 |
| 2 | Rohit | 121 |
| 3 | Kirat | 122 |
| 4 | Inder | 125 |
+----------+--------------+-----------+
部门
+----------+-----------------+
| 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="your
password",database="database_name")
cursor=db.cursor()
query="SELECT Students.Id,Students.Student_name,Department.Department_name
FROM Students INNER 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’, ‘Physics’)
注意,结果中不包括第四行,因为学生表的第四行没有在部门表中找到匹配的记录。
极客教程