Count occurrences of a word in a row in MySQL

后端 未结 9 992
野趣味
野趣味 2020-12-19 08:41

I\'m making a search function for my website, which finds relevant results from a database. I\'m looking for a way to count occurrences of a word, but I need to ensure that

9条回答
  •  眼角桃花
    2020-12-19 09:27

    create a user defined function like this and use it in your query

    DELIMITER $$
    
    CREATE FUNCTION `getCount`(myStr VARCHAR(1000), myword VARCHAR(100))
        RETURNS INT
        BEGIN
        DECLARE cnt INT DEFAULT 0;
        DECLARE result INT DEFAULT 1;
    
        WHILE (result > 0) DO
        SET result = INSTR(myStr, myword);
        IF(result > 0) THEN 
            SET cnt = cnt + 1;
            SET myStr = SUBSTRING(myStr, result + LENGTH(myword));
        END IF;
        END WHILE;
        RETURN cnt;    
    
        END$$
    
    DELIMITER ;
    

    Hope it helps Refer This

提交回复
热议问题