python不喜欢sql,试图排除多个值

mlmc2os5  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(265)

我有一个代码,下面,用户可以把过敏列表。我想让我的代码列出一个食谱列表,从用户过敏列表中排除成分。我做了一个测试代码,但不知道如何同时排除所有三种成分。

userallergy = conn.execute ('SELECT Allergies from User where userid = 4')
userallergy = userallergy.fetchall()
userallergy = userallergy[0][0].replace(" ","")
listallergy=list(userallergy.split(","))

listallergy = ["'%" + i.capitalize() + "%'" for i in listallergy]

print([listallergy])
query='SELECT RecipeName FROM Recipess where Ingredients Not LIKE {}'.format(listallergy[1])
print(query)

aller = conn.execute(query)
saferecipe = aller.fetchall()
print(saferecipe)
rt4zxlrg

rt4zxlrg1#

使用 REGEXP 对于一个干净的方法(尽管您不能直接使用它,请查看regexp python和sqlite问题的答案):

def regexp(expr, item):
    reg = re.compile(expr)
    return reg.search(item) is not None

conn.create_function("REGEXP", 2, regexp)

allergies = "|".join([i.capitalize() for i in listallergy])

print(allergies)
query='SELECT RecipeName FROM Recipess where Ingredients Not REGXP \'{}\''.format(allergies)
print(query)

一种简单的方法是通过 AND 操作符(但正如@alexis在评论中提到的,它有自己的问题):

allergies = " AND ".join(["Ingredients Not LIKE '%" + i.capitalize() + "%'" for i in listallergy])

print(allergies)
query='SELECT RecipeName FROM Recipess where {}'.format(allergies)
print(query)
qnyhuwrf

qnyhuwrf2#

您可以使用mysql regex'或'排除所有三个。您的查询应该如下所示:

query = f"SELECT RecipeName FROM `Recipess` WHERE Ingredients NOT REGEXP '{('|').join(listallergy)}'"

相关问题