从mysql中的文本字段中提取特定单词
我有一个包含文本字段的表,该字段中有大约 3 到 4 个句子,具体取决于行。
现在,我正在制作一个自动完成的 html 对象,我想开始输入单词的开头,并且数据库返回以数据库文本字段中的这些字母开头的单词。
文本字段的示例:我喜欢鱼棒,鱼帽
在我的自动完成中也很棒,如果我输入“鱼”,它会建议“鱼棒”和“鱼帽”,
除了查询之外,一切都有效。
我可以轻松找到包含特定单词的行,但无法仅提取该单词,而不能提取全文。
select data_txt from mytable match(data_txt) against('fish', IN BOOLEAN MODE) limit 10
我知道它很脏,但我无法重新排列数据库。
感谢您的帮助!
编辑:
这就是我得到的,感谢 Brent Worden,它并不干净,但它有效:
SELECT DISTINCT
SUBSTRING(data_txt,
LOCATE('great', data_txt),
LOCATE(' ' , data_txt, LOCATE('great', data_txt)) - LOCATE('great', data_txt)
)
FROM mytable WHERE data_txt LIKE '% great%'
LIMIT 10
关于如何避免一遍又一遍地使用相同的 LOCATE
表达式有什么想法吗?
I have a table that contains a text field, there is around 3 to 4 sentences in the field depending on the row.
Now, I am making an auto-complete html object, and I would like to start typing the beginning of a word and that the database return words that start with those letters from the database text field.
Example of a text field: I like fishsticks, fishhat are great too
in my auto-complete if I would type "fish" it would propose "fishsticks" and "fishhat"
Everything works but the query.
I can easily find the rows that contains a specific word but I can't extract only the word, not the full text.
select data_txt from mytable match(data_txt) against('fish', IN BOOLEAN MODE) limit 10
I know it is dirty, but I cannot rearrange the database.
Thank you for your help!
EDIT:
Here's what I got, thanks to Brent Worden, it is not clean but it works:
SELECT DISTINCT
SUBSTRING(data_txt,
LOCATE('great', data_txt),
LOCATE(' ' , data_txt, LOCATE('great', data_txt)) - LOCATE('great', data_txt)
)
FROM mytable WHERE data_txt LIKE '% great%'
LIMIT 10
any idea on how to avoid using the same LOCATE
expression over and over?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
LOCATE
查找单词的出现位置。使用
LOCATE
和之前的LOCATE
返回值来查找单词后第一个空格的出现位置。使用
SUBSTR
和前 2 个LOCATE
返回值来提取整个单词。Use
LOCATE
to find the occurrence of the word.Use
LOCATE
and the previousLOCATE
return value to find the occurrence of the first space after the word.USE
SUBSTR
and the previous 2LOCATE
return values to extract the whole word.如果行包含您可以使用的逗号 -
如果它们在表中以空格分隔,则可以将逗号替换为空格。
如果您要求数据是唯一的,您可以包括以下内容:
您可以使用 print_r 来查看数组结果的结果
这里使用 array_merge 因为如果您使用“jquery”自动完成,则 $rt 将不会显示,否则 $rt 可能会显示work 和 array_merge 可以忽略。但是,您可以通过重复前面的过程来使用 array_merge 来包含多个表。
这按字母顺序对值进行排序
If the rows contain commas you could use -
you can replace the comma for spaces if they are separated as spaces in your table.
If you require your data to be unique you may include the following:
you can use print_r to see the results of the array resulting
Here array_merge is used because $rt will not get displayed if you are using a 'jquery' autocomplete else $rt may work and array_merge can be ignored. However, you may use array_merge to include multiple tables by repeating the previous process.
This sorts the values in the alphabetic order