我有一个看起来像这样的字符串:
pi_18944000_780345308_54210001000_345900_text
如何提取并存储其中的所有ID?
我尝试过这样的事情:
set @a = (SELECT
SUBSTRING(SUBSTRING(SUBSTRING('pi_18944000_780345308_54210001000_345900_text',
(LOCATE('_', 'pi_18944000_780345308_54210001000_345900_text'))), 2), 1,
LOCATE('_', SUBSTRING(SUBSTRING('pi_18944000_780345308_54210001000_345900_text',
(LOCATE('_', 'pi_18944000_780345308_54210001000_345900_text'))), 2)) - 1)
);
select @a;
set @b = (SELECT
SUBSTRING(SUBSTRING(SUBSTRING(SUBSTRING(SUBSTRING(
'pi_18944000_780345308_54210001000_345900_text' , ( LOCATE('_', 'pi_18944000_780345308_54210001000_345900_text' )) ), 2),
LOCATE('_', SUBSTRING(SUBSTRING( 'pi_18944000_780345308_54210001000_345900_text', ( LOCATE('_', 'pi_18944000_780345308_54210001000_345900_text'
))), 2))), 2), 1, LOCATE('_', SUBSTRING(SUBSTRING(SUBSTRING(SUBSTRING( 'pi_18944000_780345308_54210001000_345900_text' , (
LOCATE( '_', 'pi_18944000_780345308_54210001000_345900_text' ))), 2),
LOCATE('_', SUBSTRING(SUBSTRING( 'pi_18944000_780345308_54210001000_345900_text', (
LOCATE('_', 'pi_18944000_780345308_54210001000_345900_text' ))) , 2))), 2)) - 1) );
select @b;
这有效,但确实很复杂。 只是想看看是否有更好的方法可以做到这一点?
答案 0 :(得分:2)
这是一个稍微简单的解决方案。它使用SUBSTRING_INDEX()
内置函数。只需引用一次字符串表达式。
mysql> set @str = 'pi_18944000_780345308_54210001000_345900_text';
mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@str, '_', 3), '_', -1) AS n;
+-----------+
| n |
+-----------+
| 780345308 |
+-----------+
请参见https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring-index
如果您需要在SQL表达式中引用单个ID,那么下次您不应该考虑在字符串中不存储多个ID。