pymysql中多条件,组合条件查询
时间: 2023-10-24 16:07:26 浏览: 70
可以使用AND或OR关键字来组合多个条件查询。
例如,查询年龄大于等于18且性别为女的用户:
```
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='password', db='test')
cursor = conn.cursor()
sql = "SELECT * FROM users WHERE age >= 18 AND gender = 'female'"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
print(row)
conn.close()
```
另外,可以使用括号来优先处理条件的组合,例如查询年龄大于等于18且性别为女,或者年龄大于等于30的用户:
```
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='password', db='test')
cursor = conn.cursor()
sql = "SELECT * FROM users WHERE (age >= 18 AND gender = 'female') OR age >= 30"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
print(row)
conn.close()
```
阅读全文