Home > Database > Mysql Tutorial > body text

How to Insert Data into MySQL Tables with Foreign Key Constraints?

Barbara Streisand
Release: 2024-10-31 04:27:31
Original
358 people have browsed it

How to Insert Data into MySQL Tables with Foreign Key Constraints?

Inserting Data into Tables with Foreign Key Constraints in MySQL

Tables involving foreign key relationships require special considerations when inserting data to ensure data integrity. Let's explore how to handle insertions in MySQL for two scenarios:

Case 1: Inserting a Student with a Pre-existing Teacher

If you have a student record to insert and the teacher they belong to already exists, you can use a subquery to retrieve the foreign key (id_teacher) based on the teacher's name:

<code class="sql">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</code>
Copy after login

Case 2: Inserting a Student with a New Teacher

If the student's teacher does not yet exist in the database, you need to perform two separate insert operations:

  1. Insert the new teacher record into the TAB_TEACHER table:
<code class="sql">INSERT INTO TAB_TEACHER(name_teacher)
VALUES ('Dr. Smith')</code>
Copy after login
  1. Use the id of the newly created teacher (id_teacher) as the foreign key when inserting the student:
<code class="sql">INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
VALUES ('Mary The Student', LAST_INSERT_ID())</code>
Copy after login

The above is the detailed content of How to Insert Data into MySQL Tables with Foreign Key Constraints?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!