访问SQL查询:返回值不在相关表的间隔之间

时间:2016-06-25 05:12:41

标签: sql ms-access between

我有两个与名称字段相关的表格(间隔和深度)。我希望查询返回每个名称不在Intervals表中的所有深度(或者不等于Top或Bottom之间或之间)。在“间隔”表中有多个“名称”记录时,我的查询失败(例如:“名称”字段中有2个'一个'记录)。

间隔

Name    Top    Bottom
one     2      3
one     5      7
two     2      3
three   3      4

深渊

Name    Depth
one     1
one     2
one     3
one     4
one     5
one     6
one     7
one     8
two     1
two     2
two     3
two     4
two     5
three   1
three   2
three   3
three   4
three   5

我的查询:

SELECT Intervals.Name, Depths.Depth
FROM Depths INNER JOIN Intervals ON Depths.Name = Intervals.Name
WHERE (((Depths.Depth) < [Intervals]![Top] 
    Or (Depths.Depth) > [Intervals]![Bottom]))
ORDER BY Intervals.Name, Depths.Depth;

我知道这会失败,因为Where子句是单独应用于Interval中的每个Name记录的。 Where子句应该适用于与Name相关的所有Interval记录,因此结果不包括Interval表中的Top to Bottom间隔。

我的查询输出:

Name    Depth
one     1
one     1   
one     2    
one     3
one     4    
one     4
one     5
one     6
one     7
one     8   
one     8
three   1
three   2
three   5
two     1
two     4
two     5

所需输出:所有深度不以间隔

Name    Depth   
one     1       
one     4       
one     8       
two     1
two     4
two     5
three   1
three   2
three   5

1 个答案:

答案 0 :(得分:2)

您的问题的措辞提示not exists,因此这可能对您有用:

select d.*
from depths as d
where not exists (select 1
                  from intervals as i
                  where i.name = d.name and d.depth between i.[top] and i.[bottom]
                 );