我正在研究搜索/标签系统。我写的原始查询是在我的文章/视频表中存储“标题”,“描述”和逗号分隔的“标签”列时。我已经意识到标准化我的标签的优势。我现在有三张表来处理...
tbl_Articles
tbl_tag_index
tbl_tag_word
此查询返回标记...只有问题是它将它们作为不同的行返回。我想我需要将结果分组到同一行,以便我的搜索查询可以正常工作
SELECT *
FROM `tbl_articles` A
JOIN `tag_index` I ON A.article_id = I.tag_target_id
JOIN tag_word W ON I.tag_word_id = W.tag_word_id
WHERE I.tag_type_id = 1
这是我以前的旧搜索查询
SELECT *,
(
(CASE WHEN `description` LIKE '%hotel%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%london%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%lazy%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%dog%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%hotel%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%london%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%lazy%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%dog%' THEN 1 ELSE 0 END) +
(CASE WHEN `tags` LIKE '%hotel%' THEN 1 ELSE 0 END) +
(CASE WHEN `tags` LIKE '%london%' THEN 1 ELSE 0 END) +
(CASE WHEN `tags` LIKE '%lazy%' THEN 1 ELSE 0 END) +
(CASE WHEN `tags` LIKE '%dog%' THEN 1 ELSE 0 END)
) AS relevance
FROM `tbl_Articles`
WHERE `description` LIKE '%hotel%'
OR `description` LIKE '%london%'
OR `description` LIKE '%lazy%'
OR `description` LIKE '%dog%'
OR `title` LIKE '%hotel%'
OR `title` LIKE '%london%'
OR `title` LIKE '%lazy%'
OR `title` LIKE '%dog%'
OR `tags` LIKE '%hotel%'
OR `tags` LIKE '%london%'
OR `tags` LIKE '%lazy%'
OR `tags` LIKE '%dog%'
ORDER BY relevance DESC
LIMIT 0 , 10;
答案 0 :(得分:3)
使用:
SELECT A.*,
GROUP_CONCAT(DISTINCT w.tag_word ORDER BY w.tag_word ASC SEPARATOR ',') AS tags,
COUNT(DISTINCT w.tag_word) +
(CASE WHEN `description` LIKE '%hotel%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%london%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%lazy%' THEN 1 ELSE 0 END) +
(CASE WHEN `description` LIKE '%dog%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%hotel%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%london%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%lazy%' THEN 1 ELSE 0 END) +
(CASE WHEN `title` LIKE '%dog%' THEN 1 ELSE 0 END) AS relevance
FROM tbl_articles A
JOIN tag_index I ON A.article_id = I.tag_target_id
JOIN tag_word W ON I.tag_word_id = W.tag_word_id
WHERE I.tag_type_id = 1
AND w.tag_word IN ('hotel', 'london', 'lazy', 'dog')
GROUP BY a.article_id, a.title, a.description, a.content
ORDER BY relevance DESC