如何同时获取与某些标签相关的帖子?

时间:2016-06-19 14:56:58

标签: mysql

我正在尝试查询posts that have all of the given tags

我有posts that have one of the given tags的查询。

我的查询是:

select * from `blog_posts` 
    inner join `blog_post_tag` on `blog_posts`.`id` = `blog_post_tag`.`post_id` 
    where `blog_post_tag`.`tag_id` in (?, ?) 
      and `blog_posts`.`deleted_at` is null

例如:

| post_id | tag_id |
|---------+--------|
|       1 |      1 |
|       1 |      2 |
|       2 |      1 |
|       3 |      2 |
  • 对于给定的代码[1],结果应该会为我提供包含12的帖子。

  • 对于给定的代码[1, 2],结果应该会为我提供标识为1 (不是[1, 2, 3]的帖子。

1 个答案:

答案 0 :(得分:0)

我能够通过以下方式获得预期的结果:

select * from `blog_posts` 
    inner join `blog_post_tag` on `blog_posts`.`id` = `blog_post_tag`.`post_id` 
    where `blog_post_tag`.`tag_id` in (?, ?) 
      and `blog_posts`.`deleted_at` is null 
    group by `blog_post_tag`.`post_id` 
    having COUNT(DISTINCT `blog_post_tag`.`tag_id`) = 2