我想查询具有不同条件的表,但这取决于客户端输入,例如:
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'))
但是,有时候,用户不想按国家/地区进行过滤,因此他们可能只会获得keyword
。所以我的查询应该像这样:
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
,但是在我的实际项目中,它有很多过滤条件,这可能会让我建立许多条件检查,例如: / p>
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语法,但是您能帮我找到一个好的语法吗?
答案 0 :(得分:1)
使用存储过程。
下面是一个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
答案 1 :(得分:0)
您可以这样使用:
sql = """SELECT * FROM t_user WHERE f_username like '%s%' and f_country like = "%s%"."""
链接> [1]:http://2015.padjo.org/tutorials/sql-basics/fuzzy-matching-like-in-where/
答案 2 :(得分:0)
如果可以的话,最好将参数与sql分开。然后,您可以让db模块处理参数的正确引用。
sql="""SELECT * FROM t_user WHERE f_username like '%s'."""
args=[beginningOfString+'%']
cursor.execute(sql,args)