MySQL Second (or third) Index Of in String

You would want to use SUBSTRING_INDEX function like this

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(field, ' ', 3), ' ', -1)
FROM table

The inner function call would get you to AAAA BBBB CCCC while the outer function call would pare that down to just CCCC.


Generally you can select the nth word in a string using:

SET @N = 3; -- 3rd word
SET @delimiter = ' ';
SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(words, @delimiter, @N), @delimiter, -1)
FROM
  my_table


DROP FUNCTION IF EXISTS `Find_string_by_position`$$

CREATE DEFINER=`root`@`localhost` FUNCTION
`Find_string_by_position`(str VARCHAR(255), delimeter VARCHAR(255),pos INT(2)) RETURNS VARCHAR(255) CHARSET utf8mb4 BEGIN
       DECLARE s VARCHAR(255);  
       DECLARE d VARCHAR(255); 
       DECLARE p INT DEFAULT 1;
       DECLARE val VARCHAR(255);


       SET s = LCASE(str); 
       SET d = delimeter;
       SET p = pos;
       SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(s,d,p),d,-1) INTO @val; 

       RETURN @val;  

   END$$

DELIMITER ;

Tags:

Mysql

Indexof