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;