droptable if exists students; droptable if exists classes; dropview if exists student_in_class; createtable classes( id serial, name char(55) notnull, unique key cls_name (name), primary key(id) ); createtable students( number char(11) notnull, name varchar(55) notnull, class_id bigint unsigned notnull, primary key(number), foreign key (class_id) references classes(id) );
为了查询数据方便,创建一个视图,只是简单的执行级联查询:
1 2 3 4 5
createview student_in_class as select number, students.name stu_name, classes.name cls_name from students innerjoin classes on classes.id=students.class_id;
dropprocedure if exists insert_stu; createprocedure insert_stu( cls_name char(55), stu_num char(11), stu_name varchar(55)) begin declare cls_id bigint unsigned; declare cls_cnt int; selectcount(*) into cls_cnt from classes where name=cls_name; if cls_cnt =0then insertinto classes(name) value(cls_name); set cls_id = last_insert_id(); else select id into cls_id from classes where name=cls_name; end if; insertinto students(number, name, class_id) values(stu_num, stu_name, cls_id); end;