[英]MYSQL : Find the last occurrence of a character in a string
长度将是动态的,我想在MYSQL中的字符串中最后一次出现字符之前找到数据
像php中的strrchr一样
要获得_(下划线)的最后一次出现,我需要传递长度。 这里是3
mysql> SELECT SUBSTRING_INDEX ('this_is_something_here', '_', 3); +----------------------------------------------------+ | SUBSTRING_INDEX ('this_is_something_here', '_', 3) | +----------------------------------------------------+ | this_is_something | +----------------------------------------------------+
在这里,要获得_(下划线)的最后一次出现,我需要传递长度。 而这里是6
mysql> SELECT SUBSTRING_INDEX ('and_this_may_go_like_this_too', '_', 6); +-----------------------------------------------------------+ | SUBSTRING_INDEX ('and_this_may_go_like_this_too', '_', 6) | +-----------------------------------------------------------+ | and_this_may_go_like_this | +-----------------------------------------------------------+
我想要在上一个示例中最后一次出现_(下划线)之前的数据字符串,但没有传递长度。
注意:从上面的例子我想要“_here”和“_too”的数据之前
最后一次出现的_(下划线)
在MySQL中是否有任何内置功能可以实现这一点?
在此先感谢amigos。
我没有得到你的例子,但我认为你想要的是传递-1作为长度并在前面加上子串。
相比
strrchr('and_this_may_go_like_this_too', '_'); // Returns _too
SELECT SUBSTRING_INDEX('and_this_may_go_like_this_too', '_', -1);
-- Returns too, just need to concatenate `_` so...
SELECT CONCAT('_', SUBSTRING_INDEX('and_this_may_go_like_this_too', '_', -1));
-- Returns _too
如果您要在针头之前和之前寻找字符串的一部分,而不是从针头到字符串的末尾,您可以使用:
SET @FULL_STRING = 'this_is_something_here';
SELECT LEFT(@FULL_STRING, LENGTH(@FULL_STRING) - LOCATE('_', REVERSE(@FULL_STRING)));
-- Returns this_is_something
请注意,第二个语句不是 strrchr
所做的。
select reverse(substr(reverse('this_is_something_here'), 1+locate('_', reverse('this_is_something_here'))));
使用反向,定位,然后更换,不使用长度
Set @str = 'there_is_something';
Select replace(@str,right(@str,locate('_',reverse(@str))),'');
你可以写这样的查询
SELECT SUBSTRING_INDEX('and_this_may_go_like_this_too','_',(LENGTH('and_this_may_go_like_this_too')-LENGTH(REPLACE('and_this_may_go_like_this_too' ,'_',''))) - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.