Я пытаюсь найти, если все слова содержатся в длинном тексте.
SELECT *
FROM
(SELECT substring_index(`sentence`, ' ', 1) AS first_keyword,
substring_index(substring_index(`sentence`, ' ', 2), ' ', -1) second_keyword
FROM `keywords`) k
LEFT JOIN `article_table` a
ON
a.article_title LIKE concat('%', k.first_keyword, '%') AND
a.article_title LIKE concat('%', k.second_keyword, '%')
http://sqlfiddle.com/#!9/ce6d67/5/0
Это отлично работает, но требует большого количества SQL, который не очень читабелен, и не масштабируется, так как я не могу добиться чего-то похожего, если слова 3 или 4.
Я совершенно новичок в написании хранимой процедуры . Я нашел этот пример , но я хотел бы понять, есть ли лучший способ разбить предложение на слова.
Любое предложение?
DELIMITER $$
DROP PROCEDURE IF EXISTS `ContainsAllWords` $$
CREATE PROCEDURE `ContainsAnyWord`(_list MEDIUMTEXT)
BEGIN
DECLARE _next TEXT DEFAULT NULL;
DECLARE _nextlen INT DEFAULT NULL;
DECLARE _value TEXT DEFAULT NULL;
iterator:
LOOP
-- exit the loop if the list seems empty or was null;
-- this extra caution is necessary to avoid an endless loop in the proc.
IF LENGTH(TRIM(_list)) = 0 OR _list IS NULL THEN
LEAVE iterator;
END IF;
-- capture the next value from the list
SET _next = SUBSTRING_INDEX(_list,',',1);
-- save the length of the captured value; we will need to remove this
-- many characters + 1 from the beginning of the string
-- before the next iteration
SET _nextlen = LENGTH(_next);
-- trim the value of leading and trailing spaces, in case of sloppy CSV strings
SET _value = TRIM(_next);
-- rewrite the original string using the `INSERT()` string function,
-- args are original string, start position, how many characters to remove,
-- and what to "insert" in their place (in this case, we "insert"
-- an empty string, which removes _nextlen + 1 characters)
SET _list = INSERT(_list,1,_nextlen + 1,'');
END LOOP;
END $$
DELIMITER ;
ВЫБРАТЬ *
ОТ keywords
К
LEFT JOIN article_table
a
НА
a.article_title ContainsAllWords (k.sentence)