简体   繁体   English

MySQL从列返回仅模式匹配

[英]Mysql return only pattern match from column

I have a column with a product description. 我有一列产品说明。 I want to do a search on this column with a regexp and only return the match from the regexp instead of the complete content of the column. 我想使用regexp在此列上进行搜索,并且只从regexp返回匹配项,而不是该列的完整内容。

ie I have a description 即我有一个描述

This magnificent bead is high on detail 这颗宏伟的珠子细节丰富

and

The bracelet has a magnetic closure 手链有磁性扣

SELECT description FROM products WHERE description RLIKE"'magn.*\s"

This should return magnificent and magnetic 这应该返回宏伟磁性

SELECT description FROM products WHERE description RLIKE"'magni.*\s"

This should return magnificent 这应该返回辉煌

But of course this current queries return the complete descriptions. 但是,当然,此当前查询返回完整的描述。 Any pointers how I could do this. 任何指针我该怎么做。 MYSQL 5.5 MYSQL 5.5

If you are using MySQL version 8.0, you can use regexp_substr() for this purpose. 如果使用的是MySQL 8.0版,则可以为此使用regexp_substr()。 This function wasn't available in earlier versions. 此功能在早期版本中不可用。

https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-substr https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-substr

UPDATE UPDATE

Here's another crack at it which should be 5.5 friendly. 这是另一个需要5.5友好的地方。 Assumes that the supplied regex is at the start of the required match. 假定提供的正则表达式位于所需匹配项的开头。

SELECT 
SUBSTRING_INDEX(
  SUBSTRING(`description`, LOCATE('magni', `description`)), ' ', 1) 
FROM table1 
WHERE `description` REGEXP 'magni';

And a working version 8.0 example for whoever upvoted my previous effort 还有一个工作版本8.0的示例,该示例适用于谁曾支持我先前的工作

SELECT REGEXP_SUBSTR('Those magnificent men in their flying machines', '[[:space:]]magni[^ ].*[[:space:]]');
    You can use REGEXP in mySql to solve your problem like:

SELECT description FROM products WHERE description REGEXP 'magn.*'
    The above query will give u result magnificent and magnetic

SELECT description FROM products WHERE description REGEXP 'magni.*'
    The above query will give u result magnificent 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM