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


12

我有三张桌子

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例如),并要求插入teacher_idclassroom基于表idteachers表,我会做:

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

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

Answers:


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';

小心。这是笛卡尔积。解决此问题的另一种方法是

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);

谢谢先生,我可以在这里使用内部联接吗?
巴巴甘德夫2014年

不需要INNER JOIN自已teachersstudents也没有外键关系。
RolandoMySQLDBA 2014年

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'));

1
INSERT INTO newtable(value1, value2, value3) 
SELECT value1N, value2N, value3N,(SELECT valueN4 FROM secondtable WHERE id='1') 
FROM firsttable WHERE id='1');

这将把结果表放在firsttable中value1N, value2N, value3N,并将来自secondtable的结果valueN4

结果:

  • 第一张表--- |username|password |name|---(有3个值,但我们使用一个)
  • 第二张表--- |id_number|Adress|tel|---(有3个值,我们全部使用)
  • 查询后的newtable将被填充--- |id_number|Adress|tel|username|-----(我们得到4个值:第二个表中的3个值和第一个表中的1个值:
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.