gpt4 book ai didi

python - mysql中如何查询数据库中条件是否存在?

转载 作者:行者123 更新时间:2023-11-29 09:49:10 28 4
gpt4 key购买 nike

我想用不同的条件查询我的表,但这取决于客户端输入,例如:

SELECT * FROM t_user WHERE f_username like 'frank' and f_country = "%UK%".

由于我用 Python 编写了服务器,所以我的查询将是:

sql = """SELECT * FROM t_user WHERE f_username like '%s' and f_country = "%%s%"."""
cur.execute(sql, ('frank', 'UK'))

但是,有时,用户不想按国家/地区进行过滤,因此他们可能只会获得关键字。所以我的查询应该是这样的:

SELECT * FROM t_user WHERE f_username like 'frank'

另外,我的Python将是这样的:

sql = """SELECT * FROM t_user WHERE f_username like '%s'"""
cur.execute(sql, ('frank',))

然后,我可以检查参数,决定应该使用哪个sql,但是在我的实际项目中,它有很多过滤器需求,这可能会让我构建很多很多条件检查,一些东西像:

if not country_id and not city_id and not keyword:
condition = """
WHERE f_username=%s
"""
elif country_id and not city_id and not keyword:
condition = """
WHERE f_username=%s and f_country=%s
"""
elif not country_id and city_id and not keyword:
condition = """
WHERE f_username=%s and f_city=%s
"""
elif not country_id and not city_id and keyword:
condition = """
WHERE f_username=%s and f_activity_title like (%%s%)
"""
elif country_id and city_id and not keyword:
condition = """
WHERE f_username=%s and f_country=%s and f_city=%s

无论如何,它有效。但我想要它更Pythonic,比如:

WHERE f_username=(%s or '*')  and f_country=(%s or '*' and f_city=(%s or '*)

我知道它并不是真正正确的 SQL 语法,但是你能帮我找到一个好的语法吗?

最佳答案

使用存储过程。

下面是一个 MySQL 过程示例:

(更新):

CREATE PROCEDURE country_hos
(IN country CHAR(50))
(IN Info CHAR(50))
begin
select * from t where
(country=@country OR @country is null) and
(info like '%'+@info+'%') -- if info is not provided and @info is empty then an empty string will return all the data.
End

SQL Server 过程示例:

create proc sp_someCatchyName
@country varchar(50),
@Info varchar(50)
as
begin
select * from t where
(country=@country OR @country is null) and
(info like '%'+@info+'%') -- if info is not provided and @info is empty then an empty string will return all the data.
end

但是,如果您计划按照 SQL 聊天室中的对话在 python 中执行内联 SQL,那么在对 python 代码进行一些搜索之后(虽然我不知道 python),以下代码应该通过以下方式为您提供工作方向:您可以实现您的目标:

内联 python sql 代码示例:

sql = """SELECT * FROM t_user WHERE f_username like '%s' and (f_country = "%%s%" OR %s is null)."""

cur.execute(sql, ('frank', 'UK')) //when both params given
cur.execute(sql, ('frank', null)) //when country is not given

关于python - mysql中如何查询数据库中条件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55135980/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com