《SQL高級應用和數據倉庫基礎(MySQL版)》作業 ·005

問題列表

1.使用如下語句,創建學生表student和班級表class 
create table student( -- 學生表
	xh char(4),         -- 學號
	xm varchar(10),     -- 姓名
	sex char(2),        -- 性別
	birthday date,      -- 出生日期
	sal double(7,2),    -- 獎學金
	studentcid int(2),  -- 學生班級號 
);

create table class( -- 班級表
	classid int(2),   -- 班級編號
	cname varchar(20),-- 班級名稱
	ccount int(3)     -- 班級人數
 );
2.基於上述學生表和班級表,完成如下問題 
(1)添加三個班級信息爲:
		1, JAVA1班, null
		2, JAVA2班, null
		3, JAVA3班, null
(2)添加學生信息如下:
		'A001', '張三', '男', '01-05-05', 100, 1
(3)添加學生信息如下:
		'A002', 'MIKE', '男', '1905-05-06', 10, 2
(4)插入部分學生信息:
		'A003', 'JOHN', '女'
(5)將A001學生性別修改爲'女' 
(6)將A001學生信息修改如下:
		性別爲男,生日設置爲1980-04-01
(7)將生日爲空的學生班級修改爲Java3班
(8)請使用一條SQL語句,使用子查詢,更新班級表中每個班級的人數 字段

參考題解

/*
* 注:建議在創建表之前,確認當前數據庫的字符集是utf8,否則後面插入中文可能會失敗。
**/

-- 1.添加三個班級
insert into class
values
	(1, 'JAVA1班', null),
	(2, 'JAVA2班', null),
	(3, 'JAVA3班', null);

-- 2.添加一個學生信息
insert into student
values('A001', '張三', '男', '01-05-05', 100, 1);

-- 3.添加一個學生信息
insert into student
values('A002', 'MIKE', '男', '1905-05-06', 10, 2);

-- 4.插入一個學生部分信息
insert into student(xh, xm, sex)
values('A003', 'JOHN', '女');

-- 5.修改一個學生性別
update student
set sex='女'
where xh='A001';

-- 6.修改一個學生部分信息
update student
set sex='男', birthday='1980-04-01'
where xh='A001';

-- 7.修改所有滿足條件的學生的班級
update student
set studentcid=(select classid from class where cname='JAVA3班')
where birthday is null;

-- 8.子查詢更新班級人數
delimiter $$ 
	create procedure getStuNum()
	begin
		declare cid_i int(2);
		declare done int default false;
		declare cur cursor for select classid from class;
		declare continue handler for not found set done=true;
		
		open cur;
		fetch cur into cid_i;
		while(not done) do
			update class
			set ccount=(select count(*) from student where studentcid=cid_i)
			where classid=cid_i;
			
			fetch cur into cid_i;
		end while;
		close cur;
	end$$ 
delimiter ;

call getStuNum();
修改標註:
	1、將原題文本部分的建表語句進行了優化
	2、將原題的2中的(2)的日期從'01-5月05'改爲了'01-05-05'
	3、將原題中2中的(3)的學生信息加上了其班級編號爲2
	(因爲原題有區分添加學生信息和插入部分學生信息,就算真的是部分信息也不難實現插入)

注:

第8題的常規寫法如下:

update class
set ccount=(select count(*) from student where student.studentcid=class.classid);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章