gpt4 book ai didi

python - 使用多个单词搜索(SQLite3)数据库

转载 作者:行者123 更新时间:2023-11-30 22:37:13 25 4
gpt4 key购买 nike

(如果您能想到更好的标题,请说出)

所以我有一个包含我希望能够搜索的表格的数据库。搜索,我有输入 intel core i5,我想获取名称列具有 intelcorei5 的任何行 其中以任何排列方式,围绕这些单词或任何其他单词的字符。

到目前为止我正在做:

search = "intel core i5" # This is taken from an entry field.
words = []
for word in search.split()
words.append("%" + word.strip() + "%")
results = db_handler.query("""SELECT Table1.ID
FROM Table1
JOIN Table2
ON Table1.ID2 = Table2.ID
WHERE Table2.Name LIKE({0}) AND
Active=1""".format(", ".join("?" for _ in self.words)), self.words)
# db_handler.query is a method which queries and returns results. Plus some other stuff.
# In Table1 there is some columns like ID, ID2, Active, eta
# ID2 matches ID in Table2 which also contains Name
# So I want ID from Table1 searched by Name from Table2

但这不起作用,因为 LIKE 不接受多个参数。 (可能有比分割输入更好的方法,但我这样做是因为这是有意义的,是吗?)我看到一些有不同问题的人被建议 REGEXP 但我已经看过了但是并没有真正得到它供我使用。如果这是最好的,你能解释一下吗,谢谢。我该怎么做?

谢谢

最佳答案

LIKE 采用一种模式,但您可以在其中包含多个关键字,例如:

... LIKE '%intel%core%i5%' ...

这将匹配包含 intel 后跟 core 后跟 i5 的值,以及之前、之后和之间的任意字符串。

要查找包含任何安排的记录,您需要使用所有排列的多个 LIKE 子句(本例中有 6 个),并将它们 OR 组合在一起,例如:

... (Table2.Name LIKE '%intel%core%i5%' OR Table2.Name LIKE '%intel%i5%core%' OR ...) ...

在上下文中:

from itertools import permutations

search = "intel core i5"
words = [word.strip() for word in search.split()]
combinations = ["%" + "%".join(order) + "%" for order in list(permutations(words)]
sql = """SELECT <Columns> FROM <Table>
WHERE [Other ...]
(<Col> LIKE {0})""".format(" OR <Col> LIKE ".join("?" for _ in combinations))
values = combinations # sql and values/combinations to be sent to a query function.

关于python - 使用多个单词搜索(SQLite3)数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944656/

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