引言
所有的演示都基于表Student,Student 的创建语句如下:
create table if not exists Student(
id int,
name varchar(20),
math float,
english float,
chinese float
);
一.新增
1.单行数据+全列插入
insert into 表名 values(字段1对应值,字段2对应值,...);
示例:
insert into Student values(9, "root", 99, 99, 99);
2.多行数据+全列插入
insert into 表名 values
(字段1对应值,字段2对应值,...),
(字段1对应值,字段2对应值,...);
行与行之间的数据需要用逗号(,)隔开
示例:
insert into Student values (1, "张三", 66, 59, 78), (2, "李四", 88, 91, 57);
3.单行数据+指定列插入
insert into 表名(字段1,字段2) values(字段1对应值,字段2对应值);
示例:
insert into Student(id, name, math, english) values(3, "尼古拉斯赵四", 66, 66);
4.多行数据+指定列插入
insert into 表名(字段1,字段2)values
(字段1对应值,字段2对应值),
(字段1对应值,字段2对应值);
行与行之间的数据需要用逗号(,)隔开
示例:
insert into Student(id, name, math, english) values
(4, "莱昂纳多傲天", 99, 67),
(5, "施瓦辛格张大三", 88, 88);
二.查询
1.全列查询
select * from Student;
2.指定列查询
select 字段1, 字段2 from 表名;
示例:
select id, name, math, english from Student;
3.查询字段为表达式
select 字段1, 字段2, 表达式 from 表名;
- 表达式不含字段
示例:
select id, name, 1024 from Student;
2.表达式包含一个字段
示例:
select id, name, math + 10 from Student;
3. 表达式包含多个字段
示例:
select id, name, math + english + chinese from Student;
4.指定别名
为查询结果的指定别名作为独立的一列进行显示
select 表达式 [as] 别名 from 表名;
as可以省略
示例:
select id, name, math + english + chinese as total from Student;
5.去重
使用distinct关键字对某列数据进行去重
select distinct 列名 from 表名;
示例:
select distinct math from Student;
6.排序
asc:按照升序(从小到大)排列
desc:按照降序(从大到小)排列
select 字段1, 字段2, ... from 表明 where 条件 order by 字段名 asc/desc;
排序规则:
- 如果不指定排序方式,默认按照升序排列;
- NULL数据的值比任何数据都小,按照升序排列排在最上面,按照降序排列排在最下面;
- 可以使用表达式的别名进行排序;
- 多个字段排序的优先级随书写顺序;
示例1:
不指定排序方式,按照升序排列
select math from Student order by math;
示例2:
NULL值的排序
select id, name, chinese from Student order by chinese;
示例3:
使用表达式的别名进行排序
select *, math + chinese + english as total from Student order by total;
示例4:
多个字段排序的优先级随书写顺序
select * from Student order by math desc, english, chinese;
7.条件查询
通过where关键字连接查询条件
(1)比较运算符
示例1:
select * from Student where math between 80 and 100;
示例2:
select * from Student where name in("张三", "李四", "王麻子");
示例3:
select * from Student where chinese is null;
示例4 :
select * from Student where chinese is not null;
示例5:
select * from Student where name like "%四";
示例6:
select * from Student where name like "张_";
(2)逻辑运算符
优先级:not > and > or
示例1:
select * from Student where math > 80 and english > 80;
示例2:
select * from Student
where not math > 90 and english > 80;
not的优先级高于and,先执行not运算,所以最后的条件是math <= 90 并且 english > 80;
三.修改
update 表明 set 字段1 = 字段1新值, 字段2 = 字段2新值
where 条件;
示例1:
update Student set chinese = 44
where name = "尼古拉斯赵四";
示例2:
update Student set math = 100, english = english + 1,
chinese = 100 where name = "root";
四.删除
1.删除特定的几行数据
delete from 表名 where 条件;
示例:
delete from Student where math > 70;
2.删除整张表数据
delete from 表名;
示例:
delete from Student;