我正在尝试查找一个查询,该查询返回在 mySQL 数据库的文本字段中找到的匹配单词列表。诀窍是文本字段包含多个我不希望返回的其他单词。
以汽车数据库为例,其中“颜色”文本字段包含汽车上的所有颜色。
假设我们的“颜色”字段中有包含这些条目的行:
"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'
理想情况下,我们可以扩展它来解释一个字段中的多次出现。例如,如果我们有一个这样的字段:“紫色、樱桃红、粉色波尔卡圆点、日落红”
最佳答案
这是一种可以做到这一点的方法,但它并不是特别“好”:
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%';
您需要手动将查询扩展到数据中最长的列表。并且,这会返回第一个匹配项,而不是全部。
关于mySQL 返回文本字段中的单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22160404/