Bab*_*dev 12 mysql relational-theory
我有三张桌子
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_id
到classroom
基于表id
的teachers
表,我会做:
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_id
从teachers
表中,也student_id
从students
表和插入双双进入classroom
表基于各自的名称?
Rol*_*DBA 15
你会写这样的查询
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';
Run Code Online (Sandbox Code Playgroud)
当心。这是笛卡尔积。解决这个问题的另一种方法是
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);
Run Code Online (Sandbox Code Playgroud)
小智 6
最简单的方法是使用子查询:
INSERT INTO classroom(teacher_id,student_id)
VALUES ((SELECT id FROM students WHERE s_name='sam'),
(SELECT id FROM teacher WHERE t_name='david'));
Run Code Online (Sandbox Code Playgroud)