2016-07-13 45 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)