[英]SQL unordered wildcard search (variable number of terms)
If want to search for a description which contains the words "hex" and "nut" I would use a query like this: 如果要搜索包含单词“ hex”和“ nut”的描述,我将使用以下查询:
cursor.execute("SELECT description FROM %s WHERE description LIKE %?% AND
description LIKE %?%" % table_name , ["hex", "nut" ])
But what if the user wants to now search for a description that contains 5 terms? 但是,如果用户现在要搜索包含5个词的描述该怎么办?
Previously in pure sql I had written something like this to generate my results: 以前在纯sql中,我曾编写过类似的代码来生成结果:
base = """
SELECT description FROM {0}
WHERE
""".format(table_name)
command = base
# Adding "AND" for each term
for i in range(len(search_terms)):
# Last portion of the SQL query
if i == (len(search_terms) - 1):
command += " description LIKE '%{0}%'".format(search_terms[i])
else:
command += " description LIKE '%{0}%' AND ".format(search_terms[i])
command = command.replace("\n", "")
cursor.execute(command)
However I was hoping there was a better way of doing this with sqlite and sql queries. 但是我希望使用sqlite和sql查询有更好的方法。 I know that I could load all the data onto memory and use pure Python to achieve what I want but I want to SQL. 我知道我可以将所有数据加载到内存中,并使用纯Python实现我想要的但我想要的SQL。 So is there an elegant and safe way of doing this? 那么,有没有一种优雅而安全的方法呢?
I'm new to stackoverflow and SQL so let me know if I asked my question wrong. 我是stackoverflow和SQL的新手,所以如果我问错了问题,请告诉我。
Consider a list comprehension with Pythons's str.join
: 考虑使用Python的str.join
进行列表理解:
table_name = 'prices' # EXAMPLE
command = """ SELECT description FROM {0} WHERE """.format(table_name)
search_terms = ['hex', 'nut', 'screw', 'bolt', 'nail'] # EXAMPLE
where = ' AND '.join(["description LIKE '%?%'" for i in search_terms])
command = command + where
print(command)
# SELECT description FROM prices WHERE description LIKE %?% AND description LIKE %?%
# AND description LIKE %?% AND description LIKE %?% AND description LIKE %?%
cursor.execute(command, search_terms) # PARAMETERIZED QUERY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.