create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2)--最大五位数字,其中两位小数 );
alter table score add constraint stu_sco foreign key(stuid) references students(id);
create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );
外键的级联操做sql
alter table scores add constraint stu_sco foreign key(stuid) reference students(id) on delete cascade;
级联操做的类型包括:数据库
例如:查询学生姓名平均分:函数
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id group by students.sname
1).查看字符的ascii码值ascii(str),str是空串时返回0ui
select ascii('a');
2).查看ascii码值对应的字符char(数字)spa
select char(97);
3).接字符串concat(str1,str2...)rest
select concat(12,34,'ab');
4).包含字符个数length(str)code
select length('abc');
5).截取字符串orm
select substring(‘abc123’,2,3);
6).去除空格blog
select trim(' deng ');--删除两侧空格 select trim(leading 'x' FROM 'xxxdengxxx');--删除左侧的x select trim(both 'x' FROM 'xxxdengxxx');--删除两侧的x select trim(trailing 'x' FROM 'xxxdengxxx');--删除右侧的x
6).返回由n个空格字符组成的一个字符串space(n)事务
select space(10);
7).替换字符串replace(str,from_str,to_str)
select replace('abc123','123','def');
8).大小写转换,函数以下
1).求绝对值abs(n)
select abs(-23);
2).求m除以n的余数mod(m,n),同运算符%
select mod(19,3); select 19%3;
3).地板floor(n),表示不大于n的最大整数
select floor(2.3);
4).天花板ceiling(n),表示不小于n的最小整数
select ceiling(2.3);
5).求四舍五入值round(n,d),n表示原数,d表示小数位置,默认为0
select round(1.234,2);
6).求x的y次幂pow(x,y)
select pow(2,3);
7).随机数rand(),值为0-1.0的浮点数
select rand();
1).获取子值,语法以下
2).日期计算,使用+-运算符,数字后面的关键字为year、month、day、hour、minute、second
select '2016-12-21' + interval 1 day;
3).日期格式化date_format(date,format),format参数可用的值以下
select date_format('2016-12-21','%Y %m %d');
4).当前日期current_date()
select current_date();
5).当前时间current_time()
select current_time();
6).当前日期时间now()
select now();
对于复杂的查询,在对次使用后,维护时一件很是麻烦的事情,视图能够解决
视图本质就是对查询的一个封装
定义视图:
create view stuscore as select students.*,scores.score from scores inner join students on scores.stuid=students.id;
视图的用途就是查询
select * from stuscore;
当一个业务逻辑须要多个sql完成时,若是其中某条sql语句出错,则但愿整个操做都退回
而使用事务能够完成退回的功能,保证业务逻辑的正确性
事务的四大特性(ACID):
表的类型必须是innodb或bdb类型,才能够对此表使用事务
查看表的建立语句:
show create table student;
修改表的类型:
alter table '表名' engine=innodb;
事务语句:
begin开启;
commit提交;
rollback回滚;
示例:
begin; insert into students (sname)values ('老细'); commit;