在查询时,通常需要只返回满足特定条件的行。所以就需要用到where来进行过滤。
where可以判断某一个属性是否和某个值相等、不等、小于、大于、不等于,在什么区间(BETWEEN AND).
select name,price
from table
where price=8 ;
select name,price
from table
where price>=8 ;
select name, price
from table
where price= BETWEEN 5 AND 8 ;
select name, price
from table
where price IS NULL; (找出价格为空值的列,这种缺失的数据需要引起我们的注意)
同时,我们还可以使用AND OR来组合不同的过滤条件,满足更复杂的需求。
select name,price
from table
where price=8 AND name=‘ddd’;
注意当AND OR混合使用时,AND优先级高,必要的时候可以加括号,括号优先级最高。
IN操作符
select name,price
from table
where name IN (‘ddd’,‘CCC’,‘AAA’);
IN操作符完成和OR同样的功能,但是更加方便。
NOT操作符
用来否定其后跟随的任何条件,相当于不等于,但是比不等于更好用,因为他可以和其他操作符联合使用,比如WHERE NOT name IN (‘ddd’,‘CCC’,‘AAA’); 可以非常方便地找出与列表不匹配的行。
LIKE以及通配符
前面都是基于已知值进行过滤。当我们需要基于某种模式进行匹配怎么办,比如匹配名字中包含’a’的所有的行。就需要用到LIKE 和通配符。
%:表示任何字符出现任意次。例如找出所有以A开头的产品;
select name,price
from table
where name LIKE ‘A%’;
例如找出所有以A开头,a结尾的产品;
select name,price
from table
where name LIKE ‘A%a’;
_:只能匹配一个任意的字符
[]: 指定一个字符集,必须匹配指定位置的一个字符
例如:找出所有以A或B开头的产品
select name,price
from table
where name LIKE ‘[AB]%’;
我们可以用脱字符^来否定[]指定的字符集
select name,price
from table
where name LIKE ‘[^AB]%’;
当然这也可以用NOT结合[]实现。
select name,price
from table
where NOT name LIKE ‘[AB]%’;
通配符很强大,但是搜索代价也很大,特别是用在搜索模式的开始处,所以有明确过滤条件尽量明确,不要过度使用通配符。