如何处理 MySQL 查询中的外键插入
为了有效地将值插入到具有外键的表中,让我们探讨两种常见的场景:
场景 1:添加学生和现有教师
要将新学生链接到现有教师,请使用教师姓名检索外键:
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;
场景2:同时创建新教师和学生
同时创建新学生和不存在的教师时:
-- Insert a new teacher first
INSERT INTO TAB_TEACHER(name_teacher)
VALUES ('Professor Jade');
-- Retrieve the newly created teacher's ID
SET @teacher_id = LAST_INSERT_ID();
-- Insert the new student with the foreign key pointing to the new teacher
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
VALUES ('Mia The Student', @teacher_id);
在此场景中,LAST_INSERT_ID() 函数用于捕获新插入的教师的 ID,以便立即用作学生的外键。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3