我正在尝试查找一个查询,该查询返回mySQL数据库中文本字段中找到的匹配单词列表。诀窍是文本字段包含多个我不想返回的其他单词。
以汽车数据库为例,其中“颜色”文本字段包含汽车上的所有颜色。
假设我们在'colors'字段中有这些条目的行:
"candy apple red, black"
"reddish brown"
"sunset red, white"
"Purple, Cherry red, pink polkadots"
"white"
"sunset red"
我可以这样做:
SELECT colours from CARS WHERE colours REGEXP 'red'
返回其中某处有“红色”的所有行,但它返回该字段中的所有内容。
诀窍是我希望结果列表看起来像这样:
"candy apple red"
"reddish brown"
"sunset red"
"cherry red"
目前我正在考虑使用PHP从服务器获取完整的结果列表,然后从那里完成列表。但是,如果数据库变大,这会花费很多。
谢谢!
编辑:
这是一个部分答案,仅包含在任何“颜色”字段中找到的第一种颜色(并删除重复项),并且查询不是太讨厌:
SELECT distinct
TRIM(CONCAT(SUBSTRING_INDEX(SUBSTRING(colours, 1, LOCATE('red',colours)-1), ',' , -1),
SUBSTRING_INDEX(SUBSTRING(colours, LOCATE('red',colours)), ',' , 1) ))as found
FROM CARS
WHERE colours REGEXP 'red'
理想情况下,我们可以将其扩展为也考虑字段中的多次出现。例如,如果我们有这样的字段:“紫色,樱桃红色,粉红色polkadots,夕阳红”
答案 0 :(得分:1)
这是一种可以做到这一点的方法,但它并不是特别“好”:
SELECT (case when substring_index(colours, ', ', 1) like '%red%'
then substring_index(colours, ', ', 1)
when substring_index(colours, ', ', 2) like '%red%'
then substring_index(substring_index(colours, 2), ', ', -1)
when substring_index(colours, ', ', 3) like '%red%'
then substring_index(substring_index(colours, 3), ', ', -1)
when substring_index(colours, ', ', 4) like '%red%'
then substring_index(substring_index(colours, 4), ', ', -1)
. . .
end)
from CARS
WHERE colours like '%red%';
您需要手动将查询扩展到数据中最长的列表。并且,这将返回第一个匹配项,而不是所有项。