繁体   English   中英

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

[英]Search (SQLite3) database using multiple words

(如果你能想到一个更好的标题,请说)

所以我有一个数据库,其中包含我希望能够搜索的表格。 搜索,因为我有输入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不会超过一个arg。 (可能有一种更好的方法,而不是分割输入,但我这样做是因为这是有意义的,是吗?)我看到一些人有一些不同的问题建议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.

让我们假设(考虑一般问题)您希望能够找到包含列表中任何或所有单词的行或在列col设置words 让我们进一步假设您完全了解SQL注入攻击的风险,因此在将其包含在words之前,您要完全清理任何用户输入。

您想要单个单词w的查询条件可以用Python表示

"{0} LIKE '%{}%'".format(col, w)

单个字段查询需要与“OR”连接以查找任何术语,或“AND”以查找所有术语。 因此,您可以将joiner设置为' AND '' OR ' ,然后整个查询搜索条件将为

joiner.join(["{0} LIKE '%{1}%'".format(col, w) for w in words])

如果你设置

words = "intel core i5".split()
joiner = " AND "
col = "Table2.name"

这评估为

Table2.name LIKE '%intel%' AND Table2.name LIKE '%core%' AND Table2.name LIKE '%i5%'

你显然已经知道足够多的Python能够用你想做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM