筛选器无法与两个where子句一起使用

时间:2018-09-03 21:23:12

标签: sql-server tsql

我有一个带有两个where子句的查询。示例代码:

   SELECT CONCAT(E.Firstname, ' ', 
            E.Middlename, ' ', 
            E.Lastname, ' ', 
            E.Maidenname, 
            ' (', E.Abbreviation, ')') AS Technician,
       'White' AS Backcolor
FROM Employee AS E
WHERE E.Empkey NOT IN (
                          SELECT Empkey
                          FROM Taskassignation AS Ta
                            INNER JOIN Task AS T ON T.Taskassignationid = Ta.Taskassignationid
                          WHERE T.Taskstatusid != '09E02513-00AD-49E3-B442-A9ED2833FB25'
                                AND T.Taskstatusid != '60F68A00-A212-4B7A-B0A3-620B5887136C'
                                AND Empkey IS NOT NULL
                                AND Terminationdate IS NULL
                          GROUP BY Empkey
                                         )
                          AND Departmentkey = 3
                          AND Terminationdate IS NULL

-- Now at the end of my second where I add two conditions:

                          WHERE T.Taskstatusid != '09E02513-00AD-49E3-B442-A9ED2833FB25' 
                          AND T.Taskstatusid != '60F68A00-A212-4B7A-B0A3-620B5887136C'
                          AND Empkey IS NOT NULL
                          AND Terminationdate IS NULL
                          AND E.Title = 'Project Technician'
                          AND E.Title = 'Project Mgr';

由于某种原因,查询不在乎我的最后条件,它只获取带有所有标题的所有值,而仅获取已经声明的标题。如果我有两个where子句,我需要指定不同的过滤器?有什么建议么?

亲切的问候。

1 个答案:

答案 0 :(得分:1)

让我们看看您的!=比较。内部选择返回不等于“ 09E ...”且不等于“ 60F ...”的所有记录。

然后,您请求不在该列表中的所有记录。因此,此结果中的每个记录都必须具有'09E ...'或'60F ...'

然后,在末尾添加WHERE子句,该子句排除所有等于'09E ...'和'60F ...'的记录。这样一无所有。

考虑以下示例:

create table Emp ( ID varchar(30), Name varchar(30) )

insert into Emp ( ID, Name ) values
('314', 'Peter'),
('09E', 'Fred' ),
('ELD', 'Wally'),
('60F', 'Mary' ),
('AOK', 'Alice')

-- List rows other than IDs 09E and 60F
select * from Emp where ID != '09E' and ID !='60F'

-- Result is:
-- ID   Name
-- 314  Peter
-- ELD  Wally
-- AOK  Alice

-- List rows that are NOT in the result set shown above

select * from Emp 
  where ID not in ( select ID from Emp where ID != '09E' and ID !='60F' )

-- Result is:
-- ID   Name
-- 09E  Fred
-- 60F  Mary

-- List all the rows above, but exclude 09E and 60F

select * from Emp 
  where ID not in ( select ID from Emp where ID != '09E' and ID !='60F' )
    and ID != '09E' and ID != '60F'

-- Result is empty
-- You've excluded all the records from the last results. 

此外,您还需要小心添加两个形式为X = A和X = B的项

create table Job ( Position varchar(30) )

insert into Job ( Position ) values
( 'CEO'         ),
( 'Technician'  ),
( 'Electrician' ),
( 'Manager'     ),
( 'Secretary'   )

select * from Job 
where Position = 'Technician'
  and Position = 'Manager'

-- Result set is empty

您可能会认为结果应该有两行。但是请考虑第二行。职位=“技术员”为true,但职位=“经理”为false。但是,您只要求第一个为真的记录,第二个也为真的记录。