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

pythonserver side programmingprogramming

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

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

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

在两个表之间应用连接时,我们需要指定将基于哪些条件连接表。

语法

SELECT column1, column2...
FROM table_1
INNER JOIN table_2 ON condition;

假设有两个表,“Students” 和 “Department”,如下所示 −

Students

+----------+--------------+-----------+
|    id    | Student_name |   Dept_id |
+----------+--------------+-----------+
|    1     |    Rahul    |    120     |
|    2     |    Rohit    |    121     |
|    3     |    Kirat    |    122     |
|    4     |    Inder    |    125     |
+----------+--------------+-----------+

Department

+----------+-----------------+
| 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’)

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


相关文章