学生课表及选课
涉及知识点:
创建数据库,创建表,外键,插入数据。
工具:datagrip
create table Students
(
Sno int primary key not null comment '学号',
Sname varchar(10) unique comment '姓名',
Ssex char(1) comment '性别',
Sage int comment '年龄',
Sdept varchar(5) comment '所在系别'
) comment '信息';
create table course1(
Con char(4) primary key ,
Cname char(40) not null ,
Cpno char(4),
Ccredit int
);
create table sc (
Sno int ,
Cno char(4),
Grade SMALLINT,
PRIMARY KEY (Sno,Cno)
);
--插入数据--
insert into Students(Sno,Sname,Ssex,Sage,Sdept) VALUES (201215121,'李永','男',20,'CS'),(201215122,'刘晨','女',19,'CS'),
(201215123,'王敏','女',18,'MA'),(201215124,'张丽','男',19,'IS');
insert into course1(con, cname, cpno, ccredit) values (1,'数据库','5',4),
(2,'数学',' ',2),
(3,'信息系统','1',4),
(4,'操作系统','6',3),
(5,'数据结构','7',4),
(6,'数据结构','',2),
(7,'PASCAL语言','6',4);
insert into sc(Sno, Cno, Grade) values (201215121,'1',92),
(201215121,'2',85),
(201215121,'3',88),
(201215122,'2',90),
(201215122,'3',80);
--外键--
alter table sc add constraint fk_sc_sno foreign key (Sno) references Students(Sno);
alter table sc add constraint fk_sc_cno foreign key (Cno) references course1(Con);
建立外键连接有两种语句,建表时建立外键,建表完成后建立外键。如上所用为建表完成后建立外键。
插入数据如遇到以下问题:MySQL 插入数据错误提示1366-Incorrect string value:'\xE6\x9D\x8E\xE5\xAD\xA6...'for column 'name' at row 1
原因是插入中文字符,但mysql默认为其他字符,所以输入不合法。
改变默认字符:alter table Student change name name varchar(40) character set utf8;
(准确指定)