选择相关标题基于与mysql类似的标签

时间:2012-11-10 06:35:59

标签: mysql sql search relevance

标签

tag_id   post_id   value
------------------------
1        1         some
2        1         good
3        1         title
4        2         some
5        2         good
6        3         some
7        4         good
8        4         title

帖子

post_id  title
-------------------
1        some good title
2        some good
3        some
4        good title

我们怎样才能在同一个post_id中获得包含值 somegood 的post_id = 1和2?

所以结果是

RESULT
title
----------
some good title
some good

good title剂量显示因为标签中的post_id = 4中没有some值。 some并未显示要求good

1 个答案:

答案 0 :(得分:3)

多次尝试LIKE

SELECT * FROM post
WHERE title LIKE '%some%'
AND title LIKE '%good%'

See this SQLFiddle

您也可以像这样加入两个表:

SELECT post.post_id, title FROM Post
RIGHT JOIN Tags
ON post.post_id = tags.post_id
WHERE Tags.value IN ('some','good')
GROUP BY post.Post_ID
HAVING COUNT(*)>1;

See this SQLFiddle

注意:如果我们不使用HAVING子句,它也会返回任何单个值存在的记录

See this SQLFiddle

See the similar requirement with similar table structure.