所有的演示都基于表Student,Student 的创建语句如下:
create table if not exists Student(
id int,
name varchar(20),
math float,
english float,
chinese float
);
insert into 表名 values(字段1对应值,字段2对应值,...);
示例:
insert into Student values(9, "root", 99, 99, 99);
insert into 表名 values
(字段1对应值,字段2对应值,...),
(字段1对应值,字段2对应值,...);
行与行之间的数据需要用逗号(,)隔开
示例:
insert into Student values
(1, "张三", 66, 59, 78),
(2, "李四", 88, 91, 57);
insert into 表名(字段1,字段2) values(字段1对应值,字段2对应值);
示例:
insert into Student(id, name, math, english) values(3, "尼古拉斯赵四", 66, 66);
insert into 表名(字段1,字段2)values
(字段1对应值,字段2对应值),
(字段1对应值,字段2对应值);
行与行之间的数据需要用逗号(,)隔开
示例:
insert into Student(id, name, math, english) values
(4, "莱昂纳多傲天", 99, 67),
(5, "施瓦辛格张大三", 88, 88);
select * from Student;
select 字段1, 字段2 from 表名;
示例:
select id, name, math, english from Student;
select 字段1, 字段2, 表达式 from 表名;
select id, name, 1024 from Student;
select id, name, math + 10 from Student;
select id, name, math + english + chinese from Student;
为查询结果的指定别名作为独立的一列进行显示
select 表达式 [as] 别名 from 表名;
as可以省略
示例:
select id, name, math + english + chinese as total from Student;
使用distinct关键字对某列数据去除重复内容
select distinct 列名 from 表名;
示例:
select distinct math from Student;
asc:按照升序(从小到大)排列
desc:按照降序(从大到小)排列
select 字段1, 字段2, ... from 表明 where 条件 order by 字段名 asc/desc;
排序规则:
示例1:
不指定排序方式,按照升序排列
select math from Student order by math;
select id, name, chinese from Student order by chinese;
select *, math + chinese + english as total from Student order by total;
select * from Student order by math desc, english, chinese;
先按照math进行降序排列,如果math值相同,按照english进行升序排列,如果english值相同,按照chinese进行升序排列
查询结果:
通过where关键字连接查询条件
运算符 | 说明 |
---|---|
>、>=、<、<= | 大于、大于等于、小于、小于等于 |
= | 等于, NULL值的比较不安全 |
<=> | 等于, NULL值的比较是安全的 |
!=、<> | 不等于 |
between x and y | 范围匹配,字段值大于等于x,并且小于等于y |
in(字段值1, 字段值2, ...) | 如果在选项中,返回true |
is null | 判断是不是NULL值,是则返回true |
is not null | 判断是不是非NULL值,是则返回true |
like | 模糊匹配 %表示任意多个字符(包括0个字符), _表示任意一个字符 |
示例1:
select * from Student where math between 80 and 100;
select * from Student
where name in("张三", "李四", "王麻子");
select * from Student where chinese is null;
select * from Student where chinese is not null;
select * from Student where name like "%四";
select * from Student where name like "张_";
运算符 | 说明 |
---|---|
and | 所有条件全为真,结果为真 |
or | 所有条件全为假,结果为假 |
not | 条件为真,结果为假;条件为假,结果为真 |
示例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 = "尼古拉斯赵四";
update Student set math = 100, english = english + 1,
chinese = 100 where name = "root";
ALTER TABLE 表名 ADD 列名 数据类型;
ALTER TABLE test01 DROP COLUMN 列名;
delete from 表名 where 条件;
示例:
delete from Student where math > 70;
delete from 表名;
示例:
delete from Student;