比较何时一个字段为空但要比较连接

时间:2014-11-18 09:41:16

标签: sql-server

我有两张桌子。

Tbl1_Students

Name Class Section  
Joe   8      A  
Pin   8      B  
Tea   8      C  
Mia   9      A  
Ton   9      B  
Mon   10  
Tim   7      A 

Tbl_Exclusion

Class Section
7       A    
8       B    
9   

查询应排除

所有记录
class= 7 and Section =A    and  
Class= 8 and Section =B    and   
Class= 9 (all the sections of 9)  

我写了下面的查询:

SELECT * FROM TBL_STUDENTS WHERE   
CLASS + ISNULL(SECTION, '') NOT IN (  
SELECT Class + ISNULL(SECTION, '') FROM tbl_EXCLUSION) 

但这不适用于案例3,如果给出单独的类名,则排除所有给出第9类忽略部分的行。

2 个答案:

答案 0 :(得分:1)

使用NOT EXISTS而不是NOT IN。它允许您在排除时使用多个字段进行比较:

SELECT  * 
FROM    tbl_Students AS s
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    tbl_Exclusion AS e
            WHERE   e.Class = s.Class
            AND     (e.Section IS NULL OR e.Section = s.Section)
        );

工作示例

CREATE TABLE #tbl_Students (Name VARCHAR(10), Class INT, Section CHAR(1));
CREATE TABLE #tbl_Exclusion (Class INT, Section CHAR(1));

INSERT #tbl_Students (Name, Class, Section)
VALUES 
    ('Joe', 8, 'A'), ('Pin', 8, 'B'), ('Tea', 8, 'C'), ('Mia', 9, 'A'), 
    ('Ton', 9, 'B'), ('Mon', 10, NULL), ('Tim', 7, 'A ');

INSERT #tbl_Exclusion (Class, Section) 
VALUES (7, 'A'), (8, 'B'), (9, NULL);

SELECT  * 
FROM    #tbl_Students AS s
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    #tbl_Exclusion AS e
            WHERE   e.Class = s.Class
            AND     (e.Section IS NULL OR e.Section = s.Section)
        );

DROP TABLE #tbl_Students, #tbl_Exclusion;

<强>结果

Name | Class | Section
-----+-------+---------
Joe  |   8   |   A
Tea  |   8   |   C
Mon  |  10   |  NULL

答案 1 :(得分:0)

我的查询至少会运行10,00,00,000行。 Gareth给出的解决方案很好,但我觉得下面的一个对我来说更清楚。 查询将是:

SELECT * 
FROM tbl_student s
WHERE 
(
    (
        s.class + ISNULL(s.section, '') NOT IN 
        (
            SELECT e.class + e.section 
            FROM tbl_exclusion e 
            WHERE e.section IS NOT NULL
        ) 
    )
    AND
    (
        s.class NOT IN 
        (  
            SELECT e.class 
            FROM tbl_exclusion 
            WHERE e.section IS NULL 
        )
    )
)