数据库
首页 > 数据库> > mysql – 如何从两个不同的表中将值插入表中?

mysql – 如何从两个不同的表中将值插入表中?

作者:互联网

我有三张桌子

students table 
------------------------------------  
id(PK, A_I)  |  student_name | nationality

teachers table
------------------------------------
id(PK, A_I)  |  teacher_name |  email

classroom table
----------------------
id(PK, A_I)   | date   | teacher_id(FK to teachers.id)  |  student_id(FK to students.id)

如果我被授予教师姓名(例如david)和student_id(例如7)并要求根据教师表中的id将teacher_id插入教室表,我会这样做:

insert into classroom (date, teacher_id, student_id)
select '2014-07-08', id, 7
from teachers
where teacher_name = 'david';

现在,如果我没有直接给出学生的身份并仅给出学生的姓名,该怎么办?假设我得到了老师的名字’david’和学生的名字’sam’.如何从教师表中获取teacher_id,从student表中获取student_id,并根据各自的名称将它们插入教室表中?

解决方法:

您可以像这样编写查询

insert into classroom (date, teacher_id, student_id)
select '2014-07-08', t.id, s.id
from teachers t,students s
where t.teacher_name = 'david'
and s.student_name = 'sam';

小心.这是笛卡尔积.另一种解决方法是

select teacher_id into @tid from teachers where teacher_name = 'david';
select student_id into @sid from students where student_name = 'sam';
insert into classroom (date, teacher_id, student_id) values ('2014-07-08',@tid,@sid);

标签:mysql,relational-theory
来源: https://codeday.me/bug/20190805/1588758.html