SQL Server:where子句被忽略

时间:2017-04-11 02:10:10

标签: sql-server

第一个条件被忽略了。

样本表和记录。

标题表:

ID  Title     Group
-------------------------
1   Header1   SERVICES
2   Header2   PACKAGING
3   Header3   COLS

表:

ID  HEADER_ID   Title   DEPARTMENT
-------------------------------------
1   1   LINE1   DEPARTMENT B
2   2   LINE2   DEPARTMENT M
3   2   LINE3   DEPARTMENT A
4   3   LINE4   DEPARTMENT C

用户故事:

  1. 我希望查询中不包含具有以下这些组的所有标头。
    • SERVICES
    • 包装
  2. 此外,我还希望其LINES位于以下部门的所有标题:
    • 部门B
    • 部门M
  3. 以下是查询:

    SELECT HEADER.*
    FROM HEADER
    INNER JOIN LINE ON HEADER.ID = LINE.HEADER_ID
    WHERE (HEADER.GROUP <> “SERVICES” OR HEADER.GROUP <> “PACKAGING”)
      AND (LINE.DEPARTMENT = “DEPARTMENT B” OR LINE.DEPARTMENT = “DEPARTMENT A”)
    

    如果删除第二个where子句,它会起作用。

1 个答案:

答案 0 :(得分:0)

您可以考虑使用子查询来查找符合您条件的所有标题(并且还要防止重复您必须使用DISTINCT或GROUP BY消除):

SELECT *
FROM HEADER
WHERE Group NOT IN ('SERVICES', 'PACKAGING') 
    AND ID IN (SELECT Header_ID FROM LINE
        WHERE DEPARTMENT IN ('DEPARTMENT M', 'DEPARTMENT B'))