仅从两个表中选择满足第二个表中多个条件的行

时间:2016-04-06 08:04:40

标签: php mysql sql

共有3个表格:

  • 帖子
  • posts_tags
  • 标记

是否可以只选择包含2个或更多特定标签的帖子?

为了选择所有带有特定标签的帖子我都这样做

SELECT * FROM posts, tags WHERE posts.id=tags.id_post AND post_tags.id_tag=1

我试过了这个查询,但它给了我post_tags.id_tag = 1或post_tags.id_tag = 2

的帖子
SELECT * FROM posts, tags WHERE posts.id=post_tags.id_post AND post_tags.id_tag IN (1,2)

2 个答案:

答案 0 :(得分:1)

SELECT posts.*
FROM posts
JOIN tags ON posts.id = tags.id_post
WHERE tags.id IN(1, 2)
GROUP BY posts.id
HAVING COUNT(tags.id_post) >= 2

答案 1 :(得分:0)

如果我理解正确的话 -

SELECT postName,count(*) as times                -- you can add fields or omit the count(*)
FROM 
(select * from posts where id in (1,2) posts     -- you can replace the whole line with `posts`. this way gives you more room for conditions
inner join 
(select * from tags where id_post in (1,2)) tags -- same as @posts
on posts.id=tags.id_post 
group by postName                                -- if you added some fieldNames at the first line - add them here too..
having times>=2
                                                 -- AND tags.id=1 -- you can specify more conditions here