3-SQL基础语法(检索、数据处理、过滤)

一、数据检索

  • 关键字可以大写、可以小写;
    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';
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • T-SQL语句创建表 如图1. IDENTITY的应用 在图1创建的两个表中,SortId和CommodityId...
    肉肉要次肉阅读 4,320评论 0 0
  • 1.查询数据 1.1简单查询 简单查询指的是仅涉及一张表的查询,例如,查询一张表中的某些列,查询一张表中满足给定条...
    谢大喵a阅读 13,217评论 3 16
  • 一、创建表 创建表Student: 创建表Course: 创建表SC: 二、修改表基本表: alter table...
    流水潺湲阅读 5,509评论 0 0
  • 回顾 字段类型(列类型):数值型,时间日期型和字符串类型 数值型:整型和小数型(浮点型和定点型) 时间日期型:da...
    翊溪阅读 4,540评论 0 0
  • 感赞安拉,感恩一切的流动和际遇。 谢谢,谢谢,谢谢爸爸和阿姨如此细心,体贴的照顾阿姨。猛烈随喜他们的孝顺,为他们创...
    黛儿微笑阅读 1,274评论 0 1