小编Bab*_*dev的帖子

如何将值从两个不同的表插入一个表?

我有三张桌子

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)
Run Code Online (Sandbox Code Playgroud)

如果我得到了老师的名字(david例如)和student_id数据(7例如),并要求插入teacher_idclassroom基于表idteachers表,我会做:

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

现在,如果我没有直接获得学生的 id 而只给我学生的名字怎么办?假设我得到了老师的名字“大卫”和学生的名字“山姆”。我如何获取teacher_idteachers表中,也student_idstudents表和插入双双进入classroom表基于各自的名称?

mysql relational-theory

12
推荐指数
2
解决办法
13万
查看次数

标签 统计

mysql ×1

relational-theory ×1