HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to insert values into a table from two different tables?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tablesinsertintodifferenttwohowvaluesfromtable

Problem

I have three tables

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)


If I was given teacher's name (david for example) and student_id (7 for example) and asked to insert the teacher_id into the classroom table based on the id in the teachers table, I would do :

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


Now, what if I was not given the student's id directly and given only the name of the student? Suppose I was given teacher's name 'david' and student's name 'sam'. How do I get the teacher_id from teachers table and also student_id from the students table and insert both into the classroom table based on their respective names?

Solution

You would write the query like this

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


Be careful. This is a Cartesian product. Another way to approach this is

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

Code Snippets

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

Context

StackExchange Database Administrators Q#71852, answer score: 16

Revisions (0)

No revisions yet.