数据库(三)
DML
这个数据库类型是最常用的数据类型。包括了增删改表中的数据。
增
格式:
insert into 表名 (列1,列2,列n) values (值1,值2,值n);
insert into stu(id,name,age) values(2,“张三”,23);
注意:
1.列和值要一一对应
2.如果列名不写的话默认为所有的列赋值。insert into stu values(值1,值2,值n);
3.除了数值不用引号,其他数值都要用引号,单引号,双引号都可以。
删
格式:
delete from 表名 where 条件;
delete from stu where age =12;
注意:
1.不写条件的话,就是把表里面的数据全部删掉,–不推荐使用有多少条数据就执行多少次删除操作,效率低
truncate table stu ; 这个方式会先删除表,然后再创建一张一样的表。–推荐使用, 效率高
改
update 表名 set 列名1= 值1,列名2=值2 加 条件;
update stu set age = 12 where name = ‘张三丰’;
注意:
1.如果不加任何条件的话,则会将表中所有的数据全部进行修改。
DQL
select * from 表名
1.语法
select
字段列表
from
表名列表
where
条件列表
group by
分组字段
having
分组之后的条件
order by
排序
limit
分页限定
2.基础查询
2-1多个字段的查询
select 字段1,字段2,字段n from 表名;
2-2去除重复
select distinct 列名 from 表名;
select distinct 列名1,列名2 from 表名;–这个要注意两个列都是一样的才能算重复。
2-3计算列
select math + english from student;
–如果有null参与的运算,计算结果都是为null
select math + ifnull(english,0) from student;
格式:
ifnull(表达式1,表达式2);null参与计算的结果都为null
–表达式1:哪个字段需要判断是否为null
–表达式2:如果该字段为null后的替换值。
--ifnull(english,0)的意思是如果English的值为null,那么就使用0替换null
2-4起别名
select math + ifnull(english,0) as 总分 from student;
--这个as可以省略。
3.条件查询
3-1where 子句后跟条件
3-2运算符
* >,<,>=<=,=,<>
## 查询年龄大于20岁的人
select * from student where age > 20;
## 查询不等于20岁的人
select * from student where age <> 20;
select * from student where age != 20;
* between…and
## 查询年龄大于等于20 小于等于30的人
select * from student age between 20 and 30;-- 推荐使用
select * from student age >=20 && age<=30; – 不推荐使用
select * from student age >=20 && age<=30;-- 不推荐使用
* in(集合)
## 查询年龄22岁,23岁,35 岁的信息
select * from student age = 22 or age =23 or age =35;
select * from student where age in (22,23,35);
* like
* ## 模糊查询,查询姓马的有哪些
* 1-1占位符
* _ : 单个任意字符
* %:多个任意字符
* select * from student where name like '马%';--这个就是不管马后面有多少个字。
* select * from student where name like '马_';--这个就是姓马两个字的马X;
* select * from student where name like '_马%';--这个查询的是第二字是马的人
* select * from student where name like '___';--这个查询的是姓名是三个字的人
* * select * from student where name like '%马%';--这个查询名字中包含马的人,这个最常用
* is null
## 查询英语成绩为null
select * from student where English = null;-- 错误的,null值不能使用 =和(!=) 判断
select * from student where English is null;
select * from student where English is not null;
* and 或者 &&
* or 或者 ||
* not 或者 !