2016-07-13 47 views
0

我在MYSQL中有两个表,其中table2包含Ids的范围,而table1包含id值。我想分开不在table2范围内的table1 ids。此查询:MYSQL - 不在所有范围

select id 
from table1,table2 
where table1.id not between table2.start and table2.end 

将导致不在至少一个范围之间的id。但我想获得不在所有范围之间的ID。

有什么想法吗?

(我不想使用反连接,因为它需要很多的资源)

回答

0

您可以使用not exists

select t1.* 
from table1 t1 
where not exists (select 1 
        from table2 t2 
        where t1.id between t2.start and t2.end 
       ); 
0

我不知道如果我这样做是正确的,但如果你想要获取不在table2的id范围之间的table1的ID,可以试试这个:

select id from table1 
       where table1.id not between 
       (select min(table2.id) from table2) and 
        (select max(table2.id) from table2)