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)
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.
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.
We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.
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
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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With