> 文章列表 > mysql小课(5)

mysql小课(5)

mysql小课(5)

null/NULL(sql不区分大小写) 表示表格里面为空错误
select * from exam_result where chinese = null;正确
select * from exam_result where chinese is null;
select * from exam_result where chinese <=> null;

注意:

使用 = 不可以处理null的比较
使用 <=> 可以处理null的比较

分页查询

limit只看前三条数据:
select * from exam_result limit 3;

limit还可以搭配offset进行查询(从0开始)

select * from exam_result limit 3 offset 0;
表示从第0条开始查询,总共查询3条数据

其中:

limit 3 offset 6 等价于 limit 6,3

查询总分前三名的同学信息:

select name,math+chinese+english as sum from exam_result order by (math+chinese+english) desc limit 3;
select name,math+chinese+english as sum from exam_result order by sum desc limit 3;

修改 :update

update 表名 set 列名 = 值,列名 = 值...where 条件; 还可以使用order by或者limit

将孙悟空的数学成绩修改为80:

update exam_result set math = 80 where name = '孙悟空';

将曹孟德的数学改为60,语文改为70:

update exam_result set math = 60,chinese = 70 where name = '曹孟德';

注意:

null在排序的时候会被当做最小的值把总成绩倒数前三的三位同学的数学成绩加上30分:
select name,math+30 as newmath,chinese+math+english+30 as sum from exam_result order by sum desc limit 3 offset 6;update exam_result set math = math + 30 order by (chinese+math+english) asc limit 3;

注意:

update exam_result set math = math + 30 where name = '唐三藏';

如果超出范围就会报错

Out of range value for column 'math' at row 1

将所有同学的语文成绩改为一半:

update exam_result set chinese = chinese*0.5 where chinese is not null;

注意:

不写where条件就是针对所有行进行操作查看警告:
show warnings;

delete删除记录(行)

delete from 表名 where 条件;还可以使用order by或者limit
将 孙 这条记录删除:
delete from exam_result where name = '孙';前面提到的where条件在这里都可以使用:
delete from exam_result where name like '孙%';

注意:

不写where并且没有limit就是对于全部数据进行操作

delete from 表名 相当于表中的数据不存在了但是表还存在
drop table 表名 相当于表都不存在了

如果执行一个sql时间比较长,可以使用Ctrl+C来取消

mysql的增删改查进阶版本

主要是复杂的查询方式

数据库的约束:

1、not null 不能为空 必填项
2、unique 唯一 让列的值唯一(不与别的行重复)
3、default 默认值
4、primary key 主键
5、foreign key 外键
6、check

1、not null

create table student (id int not null,name varchar(20) not null);

2、unique
在插入或者修改数据的时候,会先去查询,看看数据是否已经存在,如果不存在那么就可以插入或者修改数据,如果存在就会显示插入或者修改失败

没有unique条件的约束可以存在重复的数据create table student(id int unique,name varchar(20));

3、default 设置默认值

create table student(id int,name varchar(20) default'无名氏');

4、primary key 主键

要求唯一并且不可以为空
主键 = unique + not null;

mysql中要求一个表里面只可以有一个主键
创建主键的时候可以使用一个列作为主键,也可以使用多个列作为主键(复合主键)

自增主键: auto_increment

create table student(id int primary key auto_increment,name varchar(20));