一、数据检索
-
关键字可以大写、可以小写;
select/from/where…… -
查询的字段以英文逗号隔开;
-
查询字段顺序决定返回数据字段顺序;
select * from……返回表所有字段,顺序同表结构字段顺序一致; -
as : 字段别名(表别名);
-
distinct :检索字段去重;
-
目前SQL执行顺序:FROM -> SELECT;
二、数据处理
-
ORDER BY排序:升序ASC(默认),降序DESC;
多个排序规则:确定优先级,英文逗号隔开; -
LIMIT 限制返回记录的条数:limit 10;
从某个位置开始限制:limit 位置,条数;(注:第一条记录的位置是0)
limit 1,5;
三、数据过滤
-
where的操作符有 =、!=(<>)、<、<=、>、>=、between…and、in、not in;
判断是否为空:is (not) null; -
对多个条件进行处理的时候可以用 and、or 进行连接:and表示且关系,or表示或关系;
=、!=(<>)、<、<=、>、>= 用来做比较;
between … and 表示一个区间,两边都可以取到;
in、not in 是集合操作;in 表示在集合中;not in 表示不在集合中;
当需要多个条件的时候,需要用 and 或者or 去连接;and 表示 且的关系,or 是或的关系(用括号表示清楚条件关系); -
like 通配符;
百分号(%)通配符:表示任意字符;
下划线(_)通配符:只匹配单个字符; -
cast数据类型转换:cast(field as int);
-
目前SQL执行顺序:from -> where -> select -> order by -> limit;
四、举例练习

1、查询来自安徽省和江苏省的学生,都属于哪个专业;字段:学号、姓名、籍贯、专业
select stu_id as 学号,name as 姓名,from_where as 籍贯,major as 专业
from student_info
where ((from_where ='安徽省') or ( from_where='江苏省'));
2、查询年龄不是20岁的学生;字段:学号、姓名、年龄
select stu_id as 学号,name as 姓名,age as 年龄
from student_info
where age !='20';
3、查询出生日期在1995-09-01到1995-10-31的学生信息;字段:学号、姓名、出生日期
select stu_id as 学号,name as 姓名,birth_date as 出生日期
from student_info
where birth_date between '1995-09-01'and '1995-10-31';
4、查询张姓学生的学生信息;字段:学号,姓名
select stu_id as 学号 ,name as 姓名
from student_info
where name like '张%';
select stu_id as 学号 ,name as 姓名
from student_info
where name regexp '^张';
5、查询姓名中含有宇的学生信息;字段:学号、姓名
select stu_id as 学号 ,name as 姓名
from student_info
where name like '%宇%';
6、查询姓名中包含宇的学生姓名,并去重;字段:姓名
select distinct name as 姓名
from student_info
where name like '%宇%';
7、查询stu_id=201600070,学院key=a的学生信息;字段:学号,姓名,专业。(将其学院改为理学院)
select stu_id as 学号,name as 姓名,college as 学院,JSON_EXTRACT(college,'$.a')
from student_info
where stu_id='2016100070';
--将其学院改为理学院
update student_info
set major='理学院'
where stu_id='2016100070';
8、查询from_where 为null和‘’的学生信息;字段:学号、姓名、籍贯。(将他们的籍贯改为安徽省)
select stu_id as 学号,name as 姓名,from_where as 籍贯
from student_info
where ((from_where ='')
or (from_where is null));
--将他们的籍贯改为安徽省
update student_info
set from_where='安徽省'
where ((from_where ='')
or (from_where is null));
Query OK, 2 rows affected (0.02 sec)
Rows matched: 2 Changed: 2 Warnings: 0
--检查
select stu_id as 学号,name as 姓名,from_where as 籍贯
from student_info
where stu_id = '2016100050'
or stu_id ='2016100060';
网友评论