Mysql

使用 2 個外鍵向列中插入值

  • July 27, 2021

我有具有 nn 關係的表“course”和“student”,所以我創建了另一個表名“course_student”來處理它。

--Table course--
   .id            //primary key 
   .name  ```
--Table student--
   .id.          //primary key
   .name
--Table course_student
   .course_id   //primary key + foreign key course(id)
   .student_id  //primary key + foreign key student(id)

我嘗試將值插入“course_student”,但它以錯誤的語法回复

INSERT INTO course_student(course_id , student_id ) 
VALUES (
SELECT id FROM course WHERE name = "K01", 
SELECT id FROM student WHERE name = "Duy"   
);

你能幫我解決這個問題嗎?

您必須使用INSERT .. SELECT

INSERT INTO course_student ( course_id , student_id ) 
SELECT course.id, student.id
FROM course 
CROSS JOIN student 
WHERE course.name = 'K01'
 AND student.name = 'Duy';

每個子 SELECT 都需要自己的括號:

INSERT INTO course_student(course_id , student_id ) 
VALUES (
   ( SELECT id FROM course WHERE name = "K01" ), 
   ( SELECT id FROM student WHERE name = "Duy" )  
);

引用自:https://dba.stackexchange.com/questions/296221