1

我需要帮助改进下表查询中的 WHERE 子句:

Key   |   Name   |   Role   |   Location
111   |   Bob    | Manager  |  All Locations
222   |   Jim    | Manager  |  All Locations
333   |   Tim    | Sales    |  Washington
444   |   Roy    | Sales    |  New York
555   |   Lee    | Sales    |  All Locations
666   |   Gus    | Sales    |  All Locations
777   |   Joe    | Admin    |  All Locations
888   |   Jen    | Admin    |  New York

我需要排除所有“所有位置”记录,但保留角色为经理的“所有位置”记录。要获得所需的结果:

Key   |   Name   |   Role   |   Location
111   |   Bob    | Manager  |  All Locations
222   |   Jim    | Manager  |  All Locations
333   |   Tim    | Sales    |  Washington
444   |   Roy    | Sales    |  New York
888   |   Jen    | Admin    |  New York

我觉得下面的查询会排除所有的所有位置记录,包括经理的。

SELECT * FROM Table
WHERE (Location <> 'All Locations' AND Role <> 'Manager')
4

4 回答 4

4

您将要扩展WHERE

select *
from yourtable
where
(
  role = 'Manager'
  and location = 'All Locations'
)
or
(
  location <> 'All Locations'
)

请参阅带有演示的 SQL Fiddle

返回结果:

| KEY | NAME |    ROLE |      LOCATION |
----------------------------------------
| 111 |  Bob | Manager | All Locations |
| 222 |  Jim | Manager | All Locations |
| 333 |  Tim |   Sales |    Washington |
| 444 |  Roy |   Sales |      New York |
| 888 |  Jen |   Admin |      New York |
于 2013-01-15T15:53:36.787 回答
1
SELECT * FROM Table
WHERE (Location != 'All Locations' OR (Location = 'All Locations' AND Role = 'Manager')
于 2013-01-15T15:53:07.557 回答
1

您说“排除所有'所有位置'记录,但保留角色为经理的'所有位置'记录。” 这是否意味着排除角色不是经理的所有位置记录?即,您不希望包含记录 111 和 222 吗?

根据德摩根定律,Not A And Not B 等价于 Not (A or B)

在你的情况下,一个谓词是肯定的,另一个是否定的,所以德摩根会读到:

  Not (A And not B) <=> (Not A or B), i.e., 

这意味着包括所有不是所有位置或经理的记录。

如果是这样,那么您需要的是:

  ... Where Location != 'All Locations' Or Role = 'Manager'
于 2013-01-15T16:01:06.320 回答
0

您应该使用 OR 而不是 AND

SELECT * FROM Table
WHERE (Location <> 'All Locations' OR Role = 'Manager')
于 2013-01-15T15:52:50.463 回答