1.使用约束规定表中的数据规则,其中约束可以使用create table语句在创建表时规定或使用alter table语句对已有表进行更改。
其中:
not null:某列不能存null值
unique: 某列不能存在重复数据
primary key:主键,非空+不重复,确定唯一行。
foreign key:外键, 此列数据指向另一个表中的存在唯一约束的列,即此列内容必须是另一个表中列中存在的内容。
check : 用于约束列中的值的范围(mysql中暂不支持)
default: 规定默认值
已知存在student表如下
设置sid列为主键
alter table student add primary key (sid);
设置 sname列唯一
alter table student add unique(sname);
设置sage默认值为10
alter table student alter sage set default 10;
创建一个成绩表score,如下
create table score(
scid int not null,
sid int,
scourse varchar(10) not null,
sscore int,
primary key(scid),
foreign key(sid) references student(sid)
);
其中有scid主键,sid外键,指向student表中sid,科目scourse和成绩sscore列
向其中依次插入如下数据进行测试
1,3,语文,50
2,3,数学,80
3,4,语文,65
4,4,数学,70
表中存在上面4条数据后再插入如下数据将产生错误
1,3,语文,50
5,8,语文,50
6,3,null,50
2.使用alter table语句对已存在的表进行添加,修改和删除列的操作。
向student表中添加other列
alter table student add other int;
改变other列的列名和数据类型
alter table student change other newother varchar(10);
删除newother列
alter table student drop column newother;
3.使用union操作符合并两个或多个select语句的结果集,此时select语句中必须有相同数量的列,列中也必须有相似的数据类型,同时列的顺序要相同。
查询score中的scid和student中的sid,此时重复的结果将不会出现
select scid from score union select sid from student;
使用union all显示所有结果集,包含重复
select scid from score union all select sid from student;
4.使用distinct返回唯一不同值
select distinct scourse from score;
5.使用as为表或列取别名(可省略)
查询语文考了50分的学生的名字和id
select b.sid,a.sname from student as a,score b where b.scourse=’语文’ and b.sscore=50 and a.sid=b.sid;
6.使用join把两个表或多个表中的数据连接起来
其中inner join等于join:返回两表中匹配的行,即两表的交集。
left join:返回左表所有记录和右表中满足on条件的行,没有匹配数据即为null
right join:返回右表所有记录和左表中满足on条件的行,没有匹配数据即为null
full join:返回两表所有行,没有匹配数据即为null(mysql中暂不支持)
如下所示
7.嵌套查询
使用嵌套查询查询语文考了50分的学生的名字和id
select sid,sname from student where sid in (
select sid from score where scourse=’语文’ and sscore=50
);
查询平均成绩大于50的学生的名字
select sname from student where sid in(
select sid from score group by sid having avg(sscore)>50
);
查询平均成绩大于70的学生的名字
select sname from student where sid in(
select sid from score group by sid having avg(sscore)>70
);
查询平均成绩大于70的学生的名字和平均成绩
select sname,b.score from student a,( select sid,avg(sscore) score from score group by sid having avg(sscore)>70) b where a.sid=b.sid;
查询所有学生的平均成绩
select sname,b.score from student a,( select sid,avg(sscore) score from score group by sid) b where a.sid=b.sid;