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
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
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 ;
You could use SUBSTRING_INDEX.
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
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
.