select relevance title based on tag similar to like with mysql

China☆狼群 提交于 2020-01-02 09:52:52

问题


TAGS

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

POSTS

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

how can we get the post_id = 1 and 2 that contains value some and good in the same post_id?

so the result is

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

good title dosent show becouse there is no some value in post_id = 4 in tags. some doesnt show beouse the requirement good


回答1:


Try LIKE multiple time:

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

See this SQLFiddle

You can also join both tables like this:

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

Note: If we don't use HAVING clause, It will also return records where any single value exists

See this SQLFiddle

See the similar requirement with similar table structure.



来源:https://stackoverflow.com/questions/13319935/select-relevance-title-based-on-tag-similar-to-like-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!