在sqlite中多个LIKE
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在sqlite中多个LIKE相关的知识,希望对你有一定的参考价值。
我正在尝试创建一个搜索功能。
如果搜索输入字段是“foo bar”,我将其拆分为两个关键字然后执行此查询:
SELECT p.* FROM p_extra_fields as x INNER JOIN products as p ON x.product = p.id
WHERE x.type = "1"
AND
(
(x.key = "model" AND x.value LIKE "%foo%")
OR (x.key = "model" AND x.value LIKE "%bar%")
OR (x.key = "color" AND x.value LIKE "%foo%")
OR (x.key = "color" AND x.value LIKE "%bar%")
OR (x.key = "make" AND x.value LIKE "%foo%")
OR (x.key = "make" AND x.value LIKE "%bar%")
)
GROUP BY x.product LIMIT 0, 50
关键字的数量可能更高,因此我可能需要更多“喜欢”。 “钥匙”的数量也可以增加:)
有什么办法可以简化这个查询吗?我可以做像LIKE("%foo%", "%bar%")
这样的事吗?
答案
如果启用了SQLite FTS3 and FTS4 Extensions,则可以利用全文搜索(FTS)功能。您需要将p_extra_fields
表重新创建为VIRTUAL
表。然后你可以在搜索词之间插入OR
并使用MATCH
操作符...
SELECT p.*
FROM p_extra_fields x
JOIN products p ON p.id = x.product
WHERE x.key IN ('model', 'color', 'make')
AND x.type = '1'
AND x.value MATCH 'foo OR bar'
GROUP BY x.product LIMIT 0, 50;
好信息here也。点击here,在SQL Fiddle中查看它的运行情况。
另一答案
我认为这个where
条款更简单:
WHERE x.type = "1" and
x.key in ('model', 'color', 'make') and
(x.value like '%foo%' or x.value like '%bar%')
另一答案
我有同样的要求,我正在寻找一个像REGEXP "A|B|C"
匹配的机制,这意味着匹配A
,B
,C
。
所以最后这是我提出的解决方案:
WITH words(str, strSubString, hasComma) AS (
VALUES ('', "foo,bar", 1)
UNION ALL SELECT
SUBSTR(strSubString, 0,
CASE WHEN INSTR(strSubString, ',')
THEN INSTR(strSubString, ',')
ELSE LENGTH(strSubString) + 1 END),
LTRIM(SUBSTR(strSubString, INSTR(strSubString, ',')), ','),
INSTR(strSubString, ',')
FROM ssgPaths
WHERE hasComma
)
SELECT p.* FROM p_extra_fields as x INNER JOIN products as p ON x.product = p.id
JOIN words AS w ON x.value LIKE '%' || w.str || '%' AND w.str != ''
WHERE x.type = "1" and x.key in ('model', 'color', 'make');
匹配标准相当于@ Gordon的答案:
WHERE x.type = "1" and
x.key in ('model', 'color', 'make') and
(x.value like '%foo%' or x.value like '%bar%')
但是这使您可以灵活地根据查询参数动态匹配值(您可以提取出"foo,bar"
作为参数)。
例如,在不更改您的查询的情况下,您可以通过"foo,bar,boo"
直到匹配类似于正则表达式匹配:"foo|bar|boo"
以上是关于在sqlite中多个LIKE的主要内容,如果未能解决你的问题,请参考以下文章