我正在尝试查询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]
,结果应该会为我提供包含1
和2
的帖子。
对于给定的代码[1, 2]
,结果应该会为我提供标识为1
(不是[1, 2, 3]
)的帖子。
答案 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