七、过滤查询(where 子句)
where 子句中指定搜索条件,对检索数据进行过滤查询
1、过滤数据
命令:
select 字段名 from 表名 where 条件; select 字段名 from 表名 where 条件 order by 字段名;
注:在同时使用 order by 子句和 where 子句时,order by 子句应该位于 where 子句之后(先过滤出需要的数据,才能对数据进行排序)
MariaDB [test]> select * from t1 where id> 2; +----+------+------+ | id | name | sex | +----+------+------+ | 3 | er | male | | 4 | e | | +----+------+------+ 2 rows in set (0.00 sec)
2、条件操作符
= 等号 <>, != 不等于 > 大于号 < 小于号 >= 大于等于号 <= 小于等于号 and 与 or 或
MySQL在执行匹配值时,默认不区分大小写,字符串的值要用单引号(' ' )括起来,数值不需要。
3、检查该列是否有 null 值
select 字段 from 表 where 字段 is null;
4、组合 where 子句
(1) like 操作符
用于在where子句中搜索列中的指定内容,like 操作符通常和通配符配合使用
- 百分号 (%)字符来表示任意个(多个)字符,类似于UNIX或正则表达式中的星号 *。如果没有使用百分号 %, LIKE 子句与等号 = 的效果是一样的。
- 下划线(_)字符表示单个字符,即在下划线出现的地方只能表示一个字符,它和百分号除了代表的字符数不同,其用法一致
注:like 子句后面的字符串需要使用单引号( ' ' )括起来。
MariaDB [test]> select * from t1 where name like 'e%'; // 查询name字段以 e 开头的所有行记录数据 +----+------+------+ | id | name | sex | +----+------+------+ | 3 | er | male | | 4 | e | | +----+------+------+ 2 rows in set (0.00 sec)
%的位置不同,表示的含义不同:
%e 以e 结尾的所有字符串 _e
e% 以e 开头的所有字符串 e_
%e% 含有e的所有字符串 _e_
s%e 以s开头以e结尾 s_e
(2) and 和 or 操作符
and 是与运算, or 是或运算
select name,price from products where id=100 and price > 10; select name,price from products where id=100 or price > 10;
当and和or同时使用时,考虑优先级问题(and > or),所以如果需要先计算or 运算时,要用圆括号()括起来 。
(3) in 操作符
指定搜索范围,查询范围内的值,用圆括号()括起来
命令:
select 字段 from 表 where 字段 in (值1,值2...);
例如:
select name, price from products where id>=11 and id=<13; select name, price from products where id=11 or id=12; select name, price from products where id in (11,12);
in 操作符与 or 操作符功能相同。
(4) not 操作符
否定它之后所跟的任何条件(否定后跟条件的关键字)
MariaDB [test]> select * from w1 where not id=0; +------+--------+--------+ | id | addr | name | +------+--------+--------+ | 1 | 德州 | 扑克 | | 2 | 德州 | 扑克 | +------+--------+--------+ 2 rows in set (0.01 sec) MariaDB [test]> select * from w1 where id not in(1,2); +------+--------+--------+ | id | addr | name | +------+--------+--------+ | 0 | 德州 | 扑克 | +------+--------+--------+ 1 row in set (0.00 sec) MariaDB [test]> select * from w1 where not id in(1,2); +------+--------+--------+ | id | addr | name | +------+--------+--------+ | 0 | 德州 | 扑克 | +------+--------+--------+ 1 row in set (0.00 sec)

浙公网安备 33010602011771号