数据库如何同时向两张表插入一条数据

首先创建两张表:

student表:

create table student(
s_id integer primary key auto_increment comment '学号',
s_name varchar(10) comment '姓名'
)

course表:

create table course(
c_id integer primary key auto_increment comment '课程编号',
s_id integer comment '学号',
score double(10,1) comment '成绩'
)

添加外键:

#添加外键
alter table course add constraint S_ID foreign key(s_id) references student(s_id); 

#增加一个姓名为张三,课程编号为001,成绩为90.2的数据
insert into student(s_name)
values('张三');

select last_insert_id() 
into @s_id;

insert into course(s_id,c_id,score)
values(@s_id,001,90.2);

你可能感兴趣的:(sql,数据库)