MySQL Second (or third) Index Of in String

后端 未结 5 1410
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 18:19

What would be the simplest way to locate the index of the third space in a string.

My goal is to get CCC out of this space separated list: AAAA BB

相关标签:
5条回答
  • 2020-12-15 18:51

    use below query to find any random id from table after group by. Here id is the autoincrement_id.

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(id),",",FLOOR(RAND()*COUNT(DISTINCT id))+1),",",-1) AS random_id FROM tableName GROUP BY groupbyColumn

    0 讨论(0)
  • 2020-12-15 19:00
    
    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 ;
    
    
    0 讨论(0)
  • 2020-12-15 19:01

    You could use SUBSTRING_INDEX.

    0 讨论(0)
  • 2020-12-15 19:04

    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
    
    0 讨论(0)
  • 2020-12-15 19:12

    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.

    0 讨论(0)
提交回复
热议问题