从两个标签中选择发布(AND)

时间:2012-11-10 05:25:37

标签: mysql sql

标签

tag_id      tag          post_id 
--------------------------------
1           category1    1
2           category2    1
3           etc          2
4           category3    1

post_id title
-------------
1       title1

我们如何获得title1,因为它位于category1&& category2

类似

SELECT TITLE 
  FROM post, tag 
 WHERE tag.post_id = post.post_id 
   AND tags.tag = 'category1','category2'

2 个答案:

答案 0 :(得分:3)

为了检查标题是否包含'category1'和'category2',您可以使用以下SQL查询:

SELECT title 
FROM post 
JOIN tag ON post.post_id = tag.post_id 
WHERE tag.tag_id IN (SELECT tag_id FROM tag WHERE tag = 'category1')
AND tag.tag = 'category2';

要检查其他类别,只需重复WHERE子句:

SELECT title 
FROM post 
JOIN tag ON post.post_id = tag.post_id 
WHERE tag.tag_id IN (SELECT tag_id FROM tag WHERE tag = 'category1')
AND tag.tag_id IN (SELECT tag_id FROM tag WHERE tag = 'category2')
AND tag.tag = 'category3';

这将返回包含所有3个类别的标题的结果。

答案 1 :(得分:1)

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

SELECT post.* 
FROM post 
LEFT JOIN tag
ON post.post_id = tag.post_id
WHERE tag.tag IN ('category1','category2')
GROUP BY post.post_id
HAVING COUNT(post.post_id) >1;

See this SQLFiddle

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

See this SQLFiddle

See the similar requirement with similar table structure.