Sqlite查询创建问题

时间:2012-05-07 11:18:49

标签: mysql sql sqlite

有2个表

     table1                      table2

book_id | tag_id                 tag_id
----------------               -----------
  5     |   1                       1
  5     |   3                       3
  5     |   4                       4
  7     |   1
  7     |   2
  7     |   4

我需要创建sql查询以选择所有book_id,其中tag_id是table2(SQLite)中所有tag_id的众多。

例如,book_id = 5是可以接受的,因为它包含table2(1,3,4)中的所有标记。 book_id = 7的书是不可接受的,因为它只有1和4个标签,但没有tag_id = 3.

1 个答案:

答案 0 :(得分:2)

我不确定这个查询是否会非常有效,但是......

select distinct book_id from table1 x 
where not exists(
select * from table2 t where not exists(
select * from table1 a 
where a.tag_id = t.tag_id 
and a.book_id = x.book_id));

设置代码:

drop table table1;
drop table table2;
create table table1(book_id int, tag_id int);
insert into table1 values(5, 1);
insert into table1 values(5, 3);
insert into table1 values(5, 4);
insert into table1 values(7, 1);
insert into table1 values(7, 2);
insert into table1 values(7, 4);
create table table2(tag_id int);
insert into table2 values(1);
insert into table2 values(3);
insert into table2 values(4);
相关问题