2017-08-03 51 views
3

如何在同一个SELECT SQL查询中使用WHERE和WHERE?WHERE和WHERE不在SELECT中

例如,我可以有一个名为水果的表。

ID | Name  | Colour 
------------------------- 
1 | Strawberry | Red 
2 | Apple  | Red 
3 | Grape  | Red 
4 | Banana  | Yellow 

从这个表,我可以执行一个SELECT * FROM [fruits] WHERE Colour = 'Red',它会检索以下:

ID | Name  | Colour 
------------------------- 
1 | Strawberry | Red 
2 | Apple  | Red 
3 | Grape  | Red 

不过,我想从上面的单个请求排除Apple,我可以用一个WHERE NOT ,但是这会返回所有水果,包括Banana

我怎么会写一个SQL查询,以便它会造成以下的,被选择特定的颜色,但不包括特定的水果:

ID | Name  | Colour 
------------------------- 
1 | Strawberry | Red 
3 | Grape  | Red 

我使用MSSQL 2014年,任何帮助,将不胜感激。

+1

可你只是无法使用,其中name <> '苹果' –

回答

4

你可以有多个条款在where

select * 
from [fruits] 
where Colour = 'Red' 
    and Name <> 'Apple' 
+0

是,似乎已经为我工作,非常感谢你! –

+0

@SamBunting乐于助人! – SqlZim

0
select * 
from [fruits] 
where Colour = 'Red' and Name != 'Apple' 
+1

跳过那个旧的,不推荐使用'!=',用'<>'代替。 – jarlh

+2

我更喜欢使用它,因为它在每个基于'C'的语言中都可用。 – TheDetective

2

您只需使用关键字ANDOR你的WHERE子句添加多个条件语句。

例如:

SELECT * 
FROM [fruits] 
WHERE Colour = 'Red' AND NOT Name = 'Apple' 
+1

双引号用于分隔标识符。对于字符串文字使用单引号。 – jarlh

3
SELECT * 
FROM [fruits] 
WHERE 
Colour = 'Red' 
and Name <> 'Apple' 
-1

您可以编写下面的查询

SELECT * FROM [fruits] WHERE Colour = 'Red' and Name<>'Apple'; 

SELECT * FROM [fruits] WHERE Colour like 'Red' and Name not like 'Apple';