在SQL中组合2个不相似的语句

时间:2013-01-18 19:59:08

标签: sql

我有一个公式,其中我有一个区域列和一个区域列(区域由区域组成),在公式中我有一些代码片段来排除某些区域作为一个整体。但有些我只想从某些地区排除一些地区,但不是全部。代码的where部分如下所示:在代码中我想要排除区域100和区域76的所有区域,但是对于区域88,我只想排除区域04,但是当我输入这样的代码时,它会排除所有88 。(此代码中没有GROUP BY)

SELECT ID, Date, Class, Location, Training Number
FROM Table 1 INNER JOIN Table 2 ON Training Number     
WHERE (Region NOT LIKE '100') AND 
      (Region NOT LIKE '76') AND 
      (Region NOT LIKE '88') AND 
      (District NOT LIKE '04')

3 个答案:

答案 0 :(得分:5)

我不确定您使用LIKE运算符的原因,您应该可以使用:

SELECT ID, Date, Class, Location, Training Number
FROM Table 1 
INNER JOIN Table 2 
  ON Training Number     
WHERE Region <> '100' 
  AND Region <> '76'
  AND 
  (
    Region <> '88' 
    OR District <> '04'
  );

或者您可以使用NOT IN

SELECT ID, Date, Class, Location, Training Number
FROM Table 1 
INNER JOIN Table 2 
  ON Training Number     
WHERE 
(
  Region NOT IN ('100', '76')
)
AND 
(
  Region <> '88' 
  OR District <> '04'
)

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

如下:

SELECT ID, Date, Class, Location, Training Number
FROM Table 1 INNER JOIN Table 2 ON Training Number     
WHERE (Region <> '100') AND -- Region cannot be 100
      (Region <> '76') AND  -- Region cannot be 76
      (Region <> '88' OR District <> '04') -- Region cannot be 88 if District is 04

答案 2 :(得分:0)

这样做:

where Region not in ('100', '76', '88') and district <> '04'

您无需使用like