在 Mysql 中查找存储在字符串中的多个 ID

Find multiple ids stored in a string in Mysql

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