Home > Database > Mysql Tutorial > body text

How to Insert Values with Foreign Keys in MySQL Tables: Existing vs. New Keys?

Mary-Kate Olsen
Release: 2024-10-30 21:24:30
Original
480 people have browsed it

How to Insert Values with Foreign Keys in MySQL Tables: Existing vs. New Keys?

Inserting Values with Foreign Keys in MySQL Tables

In database management, it's common to create tables with foreign key constraints to establish relationships between them. This question explores how to insert values into tables with foreign keys, considering two scenarios.

Scenario 1: Inserting with an Existing Foreign Key Value

To insert a student record with an existing teacher record and retrieve the foreign key via the teacher's name, use the following query:

<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

This query ensures that the inserted student record links to the correct teacher based on the provided name.

Scenario 2: Inserting with a New Foreign Key Value

For inserting both a new student and a new teacher simultaneously, the following procedure should be followed:

  1. Insert the teacher record:

    <code class="sql">INSERT INTO TAB_TEACHER(name_teacher)
    VALUES ('Professor Jane')</code>
    Copy after login
  2. Retrieve the newly inserted teacher's ID:

    <code class="sql">SET @new_teacher_id = LAST_INSERT_ID()</code>
    Copy after login
  3. Insert the student record with the foreign key set to the new teacher's ID:

    <code class="sql">INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
    VALUES ('Mary The Student', @new_teacher_id)</code>
    Copy after login

By executing these steps, a new student record linked to the newly created teacher record will be inserted into the database.

The above is the detailed content of How to Insert Values with Foreign Keys in MySQL Tables: Existing vs. New Keys?. 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