2016-06-19 101 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 
相關問題