如果你只想要最后一个字符串,你可以先REVERSE()这个字符串,然后找到|,然后用它在反转的字符串上做SUBSTRING()。然后再次反转它以获得原始字符串细绳。如果您使用不带子查询的 SUBSTRING(),则总共有三个 REVERSE():
SELECT test_string,
REVERSE(SUBSTRING(REVERSE(test_string),1,LOCATE('|',REVERSE(test_string))-1))
FROM test_table;
如果您使用子查询,您可以将REVERSE() 的使用量减少到两个,尽管查询时间更长:
SELECT test_string,
REVERSE(SUBSTRING(rvstr,1,LOCATE('|',rvstr)-1))
FROM
(SELECT test_string,
REVERSE(test_string) rvstr
FROM test_table) a;
但您可以避免所有这些,只需使用 SUBSTRING_INDEX
SELECT test_string,
SUBSTRING_INDEX(test_string, '|', -1)
FROM test_table;
您可以使用相同的函数来提取由分隔符分隔的其他字符串,方法如下:
SELECT test_string,
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
FROM test_table;
至于“提取3号之后所有内容的方法”,我觉得有点棘手,但也许:
SELECT test_string,
Str1,Str2,Str3,
SUBSTRING(test_string,LENGTH(CONCAT(Str1,Str2,Str3))+4) AS 'StrAfter3rd'
FROM
(SELECT test_string,
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',1),'|',-1) AS 'Str1',
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',2),'|',-1) AS 'Str2',
SUBSTRING_INDEX(SUBSTRING_INDEX(test_string,'|',3),'|',-1) AS 'Str3'
FROM test_table) v;
获取Str1 到Str3 的串联结果中的LENGTH(),重新添加原始| 中的3 个,并在第四个字符串之前加上最后一个|(总共+4),然后将其用于SUBSTRING()。
Demo fiddle