【问题标题】:SQL unordered wildcard search (variable number of terms)SQL 无序通配符搜索(可变数量的词条)
【发布时间】:2016-11-19 14:29:05
【问题描述】:

如果要搜索包含单词“hex”和“nut”的描述,我会使用这样的查询:

cursor.execute("SELECT description FROM %s WHERE description LIKE %?% AND
    description LIKE %?%" % table_name , ["hex", "nut" ])

但是如果用户现在想要搜索包含 5 个术语的描述呢?

以前我在纯 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)

但是,我希望有更好的方法来使用 sqlite 和 sql 查询。我知道我可以将所有数据加载到内存中并使用纯 Python 来实现我想要的,但我想要 SQL。那么有没有一种优雅而安全的方法呢?

我是 stackoverflow 和 SQL 的新手,所以如果我问错了问题,请告诉我。

【问题讨论】:

    标签: python sql sqlite


    【解决方案1】:

    考虑使用 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
    

    【讨论】:

    • 试过这个答案,它看起来真的很漂亮,但由于某种原因我得到 `sqlite3.OperationalError: near "%": syntax error
    • 哎呀!忘记了包含通配符运算符的文字中的单引号。见编辑。我很快抓住了你的第一个 cursor.execute() 代码,认为它是完全有效的。
    猜你喜欢
    • 2014-08-22
    • 2015-04-11
    • 2019-11-03
    • 2011-05-23
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2012-08-01
    • 2011-07-14
    相关资源
    最近更新 更多