在 SQL 中高效搜索子字符串 [Python/SQLite]



我有两个SQLite表(list1list2(,每个表只有一个文本列(val(。我想有效地搜索所有组合,其中list2.value可以是list1.value中的子字符串。

目前我有这个解决方案:

import sqlite3
list1 = ["this is string1", "this is string2", "this is string3"]
list2 = ["string1", "string2"]
in_memory = sqlite3.connect(':memory:')
c = in_memory.cursor()
c.execute('CREATE TABLE list1 (val text NOT NULL)')
c.execute('CREATE TABLE list2 (val text NOT NULL)')
for v in list1:
    c.execute("INSERT INTO list1 VALUES (?)", (v, ))
for v in list2:
    c.execute("INSERT INTO list2 VALUES (?)", (v, ))
l = [*c.execute("SELECT list1.val, list2.val FROM list1, list2 WHERE instr(list1.val, list2.val)")]
print(l)

正确打印:

[('this is string1', 'string1'), ('this is string2', 'string2')]

有没有比遍历每个list1.vallist2.val组合并搜索是否有子字符串更有效的 SQL 解决方案?

您可以将其表述为单个查询:

select l1.value, l2.value
from list1 l1 join
     list2 l2
     on l1.val like '%' || l2.val || '%';

在数据库内执行循环比自己执行循环效率略高 - 因为仅返回匹配的行,并且您没有多个查询的开销。

但是,这仍将执行嵌套循环。 此类查询不能利用传统索引。

最新更新