gpt4 book ai didi

mysql - 在Mysql中查找存储在一个字符串中的多个id

转载 作者:行者123 更新时间:2023-11-29 05:49:34 25 4
gpt4 key购买 nike

我有一个看起来像这样的字符串: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;

这可行,但它真的很复杂。只是想看看是否有更好的方法来做到这一点?

最佳答案

这里有一个更简单的解决方案。它使用 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。

关于mysql - 在Mysql中查找存储在一个字符串中的多个id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com