一、过滤数据
1、使用WHERE子句
过滤数据:关键字WHERESELECT 字段列表 FROM 表名 WHERE 过滤条件;过滤条件一般由要过滤的字段、操作符、限定值三部分组成;如: SELECT student_id,student_name FROM student WHERE gender = '男';
2、常用操作符
3、过滤单个值
#age 不等于10SELECT student_id FROM student WHERE age <> 10;SELECT student_id FROM student WHERE student_name = '汪书乔';SELECT * FROM student WHERE birth_day <= '2005-12-31';
4、过滤NULL值
SELECT * FROM student WHERE age IS NOT NULL; SELECT * FROM student WHERE class_id IS NULL;#(错误写法!)SELECT * FROM student WHERE class_id = NULL;
5、过滤集合
###SELECT * FROM student WHERE age BETWEEN 10 AND 15; SELECT * FROM student WHERE birth_day BETWEEN '2005-01-31' AND '2005-12-31';###SELECT * FROM student WHERE age IN (10,11,15); SELECT * FROM student WHERE student_name IN ('叶冬星','李佳欣','汪如一');SELECT * FROM student WHERE student_id NOT IN ('S20160001','S20160002');
二、高级过滤数据
1、使用通配符过滤数据
###使用通配符过滤数据:关键字LIKE百分号 % -->匹配0~多个任意字符下划线 _ -->匹配1个任意字符方括号 [ ]、[^ ] -->匹配1个字符集中的字符基本所有的数据库都支持百分号通配符和下划线通配符,但只有很少的数据库支持方括号通配符。如: SELECT * FROM student WHERE student_name LIKE '陈%'; SELECT * FROM student WHERE student_name LIKE '%慧'; SELECT * FROM student WHERE student_name LIKE '陈_’; SELECT * FROM student WHERE student_name LIKE '陈_军';但是MySQL不支持: SELECT * FROM student WHERE student_id LIKE 'S200[678]'; SELECT * FROM student WHERE student_id LIKE 'S200[^678]';使用通配符的注意点: 不要过度使用通配符; 如果确实需要使用,也尽量不要把通配符用在匹配模式的开始处; 要特别注意通配符的位置,否则很有可能返回的结果与预期不一致;
2、组合WHERE子句
###使用逻辑操作符组合WHERE子句: AND操作符 满足所有条件 OR操作符 满足任一条件比如: 如何取出所有姓陈的男同学? SELECT * FROM student WHERE student_name LIKE '陈%' AND gender = '男'; 如何取出所有姓陈的同学或男同学? SELECT * FROM student WHERE student_name LIKE '陈%' OR gender = '男';比如: 如何取出所有年龄大于15岁并且姓陈或男性同学? 错误写法: SELECT * FROM student WHERE age > 15 AND student_name LIKE '陈%' OR gender = '男'; 正确写法: SELECT * FROM student WHERE age > 15 AND (student_name LIKE '陈%' OR gender = '男');使用组合WHERE子句时,尽量都使用括号消除歧义;