2016-06-19 66 views
1

我正在尝试查询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],结果应该给我的职位与IDS 12

  • 对于给定的标签[1, 2],结果应该给我的职务与ID 1(不[1, 2, 3]

+0

@jpw谢谢,我想...... :) –

+1

@jpw我已经做了... –

回答

1

我能够得到预期的结果:

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 
相关问题