Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert values in table with foreign key using MySQL?

I have these two tables just for example:

TAB_TEACHER - id_teacher   // primary key, autoincrement - name_teacher // a varchar  TAB_STUDENT - id_student    // primary key, autoincrement - name_student  // a varchar - id_teacher_fk // foreign key reference to a teacher (TAB_TEACHER) 

I want to know how to insert in these two cases:

CASE 1 - INSERT a new Student with an pre-existing TEACHER, so I have to get the foreign key with a teacher name

CASE 2 - INSERT a new Student with a new TEACHER (the teacher I'm creating in the same time I'm creating the student)

like image 251
okami Avatar asked Jan 23 '11 18:01

okami


People also ask

How do you insert data into a table that has a foreign key?

If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.

How do I add a foreign key constraint to existing table in MySQL?

Here's the syntax to create foreign key in MySQL. ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (foreign_key_name,...) REFERENCES parent_table(column_name,...); In the above query, table_name is the the table where you want to add foreign key.

Can I add a foreign key constraint to an existing table with data?

We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.


2 Answers

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk) SELECT 'Joe The Student', id_teacher   FROM TAB_TEACHER  WHERE name_teacher = 'Professor Jack'  LIMIT 1 

For case2 you just have to do 2 separate insert statements

like image 156
Imre L Avatar answered Oct 11 '22 12:10

Imre L


Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student     SET name_student = 'Bobby Tables',        id_teacher_fk = (        SELECT id_teacher          FROM tab_teacher         WHERE name_teacher = 'Dr. Smith') 

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher    SET name_teacher = 'Dr. Smith'; INSERT INTO tab_student     SET name_student = 'Bobby Tables',        id_teacher_fk = LAST_INSERT_ID() 
like image 34
William Entriken Avatar answered Oct 11 '22 12:10

William Entriken