如何在 Python 中使用 MySQL 对两个表执行内连接?


我们可以根据两个表之间的一个公共列或基于某些指定条件来连接 SQL 中的两个表。有多种类型的 JOIN 可用于连接两个 SQL 表。

这里,我们将讨论两个表的内连接。

JOIN 和 INNER JOIN 的工作方式相同。INNER JOIN 将一个表中的每一行与另一个表中的每一行匹配,并允许组合来自两个表的行,这些行要么具有某些公共列,要么满足指定的某些条件。

在两个表之间应用连接时,我们需要指定连接表的条件。

语法

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 查询

  • 关闭连接

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="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’)

请注意,第 4 行未包含在结果中,因为 Department 表中没有与 Students 表的第 4 行匹配的记录。

更新于: 2021年6月10日

3K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告