1

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

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

4

1 回答 1

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。

于 2019-04-15T19:56:29.260 回答