加入2个表的SQL查询

时间:2012-11-10 14:03:34

标签: mysql sql sqlite

我有2个表,book和temp_table。 书中有2列:book_id and tag_id,temp_table(tag_id)中只有1列。

我需要按照以下规则进行选择:

  • 如果book中有来自temp_table的所有标签,那么它将在结果中。

例如,有3本书。

   First one has tag_id: 1,2,3,4.
   Second - 1,3,4
   Third - 1,2,3,5

temp_table包含tag_id:1,3,4

所需选择必须包含第1和第2本书。 3d book不能在结果集中,因为它有tag_id = 5,而temp_table中没有。

1 个答案:

答案 0 :(得分:1)

select book_id
from book b
inner join temp_table t on t.tag_id = tag_id
group by book_id
having count(distinct tag_id) = (select count(distinct tag_id) from temp_table)