使用 Python 解释并展示 MySQL 中 UNION 的用法?

pythonserver side programmingprogramming

UNION 语句用于合并两个 SELECT 查询的结果,而不重复重复的值。如果两个 SELECT 查询都返回相同的行,则仅列出一次。

要对两个 select 语句执行 UNION,

  • 返回的列数必须相同

  • 列的数据类型必须相同

  • 两个 select 语句必须以相同的顺序返回列。

语法

SELECT column_name FROM table1
UNION
SELECT column_name FROM table2

在 python 中使用 MySQL 执行两个 select 查询的联合的步骤

  • 导入 MySQL 连接器

  • 导入 MySQL 连接器

  • 使用 connect() 与连接器建立连接

  • 创建使用 cursor() 方法创建 cursor 对象

  • 使用适当的 mysql 语句创建查询

  • 使用 execute() 方法执行 SQL 查询

  • 关闭连接

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

Students

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

Department

+----------+-----------------+
| Dept_id  | Department_name |
+----------+-----------------+
| 120      | CSE             |
| 121      | Mathematics     |
| 122      | Physics         |
+----------+-----------------+

我们将从两个表中选择 Dept_id 并对结果执行合并。这将返回两个表中存在的所有不同 dept_id。

示例

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT Dept_id FROM Students UNION SELECT Dept_id FROM Department"
cursor.execute(query)

rows=cursor.fetchall()
for row in rows:
   print(row)

db.close()

输出

120
121
125
123
122

相关文章