MySQL:从字符串(或varchar字段)中提取第一个,第二个和第三个单词

时间:2019-07-09 10:33:36

标签: mysql

如何在 MySQL 的varchar字段中提取第一第二单词?

1 个答案:

答案 0 :(得分:0)

只需使用SUBSTRING_INDEX(official MySQL documentationofficial MariaDb Documentation

SELECT Substring_index(`sentence`, ' ', 1)                           AS first_word, 
       Substring_index(Substring_index(`sentence`, ' ', 2), ' ', -1) AS second_word,
       Substring_index(Substring_index(`sentence`, ' ', 3), ' ', -1) AS third_word 
FROM   `test` 

https://www.db-fiddle.com/f/iSGActpsMNzHze13W2QA3q/1

也可以通过以下解决方案使其更通用:

SET @N = 3; --3rd word
SET @delimiter = ' ';
SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(`sentence`, @delimiter, @N), @delimiter, -1)
FROM
  `test`;

credits to this guy