使用Python解释和展示MySQL中UNION的用法?
使用UNION语句将两个SELECT查询的结果组合在一起,而不重复重复的值。如果两个SELECT查询返回相同的行,则只列出一次。
要执行两个select语句的UNION,
- 返回的列数必须相同
- 列的数据类型必须相同
- 两个select语句必须以相同的顺序返回列。
更多Python相关文章,请阅读:Python 教程
语法
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2
使用MySQL在python中执行两个select查询的联合的步骤
- 导入MySQL连接器
-
导入MySQL连接器
-
使用connect()方法与连接器建立连接
-
使用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,然后在结果上执行union。这将返回我们在两个表中都存在的所有独特dept_ids。
例子
import mysql.connector
db=mysql.connector.connect(host="您的主机", user="您的用户名", password="您的密码",database="数据库名")
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