包含like运算符中python列表中每个元素的多个sql查询

sy5wg1nm  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(289)

我正在尝试运行多个 SQL queries 在哪里 LIKE 运算符包含python中列表的每个元素。我有一长串的弦

l = ['string1', 'string2', 'string3',....]

query_1 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[0]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[0])
query_2 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[1]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[1])
query_3 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[2]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[1])

等等。
如何运行多个查询,然后连接它们?有没有可能使用 execute 对多个查询起作用还是只能对一个查询起作用?我会使用for循环吗?
编辑:在这个问题的前一个版本中,我问过如何在数据库中运行一个包含多个列表元素的查询 LIKE 接线员。我意识到最后的问题是:

SELECT COUNT(request) FROM table WHERE request LIKE 'l[0]' OR LIKE 'l[1]' OR LIKE 'l[2]' AND DATE BETWEEN 'date1' AND 'date2'.

那不是我需要的。

r8xiu3jd

r8xiu3jd1#

如果您不希望并行执行,只需执行以下操作(伪代码)

l = ['string1', 'string2', 'string3',....]

query_1 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[0]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[0])
query_2 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[1]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[1])
query_3 = "SELECT COUNT(request) FROM table WHERE request LIKE 'l[2]' AND DATE BETWEEN 'date1' AND 'date2'".format(l[1])
result = [] 
query_lst = [query_1 ,query_2 ,query_3]
for query in query_lst:
   temp = query.execute()
   result.append(temp)

如果您对并行执行感兴趣,请参阅此示例
https://pythonprogramming.net/values-from-multiprocessing-intermediate-python-tutorial/

wgxvkvu9

wgxvkvu92#

可以将f字符串与for循环一起使用

l = ['string1', 'string2', 'string3']
res = []
for x in l:
    query = f"SELECT COUNT(request) FROM table WHERE request LIKE '{x}' AND DATE BETWEEN 'date1' AND 'date2'"
    cursor.execute(query)
    res.append(cursor.fetchone()[0])

相关问题