Search code examples
sqlsqliteinner-joinsql-insert

Insert into a third table from two other tables with one to many relationship


I have 3 tables:

1st table - Students:

| ID       | NAME     |
| -------- | -------- |
| 1        | Student-1|
| 2        | Student-2|
| 3        | Student-3|

2nd table - Homework:

| ID       | NAME     |
| -------- | -------- |
| 1        | Homework-1|
| 2        | Homework-2|
| 3        | Homework-3|

I would like to insert each [ID from Students] to certain [ID from Homework] in 3rd Table. In the end, the 3rd table should looks like this:

3rd table - Teacher_Board:

| Student_ID | Homework_ID   |
| --------   | ------------- |
| 1          | 1             |
| 2          | 1             |
| 3          | 1             |

My SQL query:

INSERT INTO `teacher_board` (`student_id`, `homework_id`) 
    SELECT `id` 
    FROM `homework` 
    INNER JOIN `students` ON `students.id` = `teacher_board.student_id` 
    WHERE `id` = 1

Solution

  • You need to select two columns and use a CROSS JOIN

    INSERT INTO `teach_board` (`student_id`,`homework_id`) 
    
    SELECT
    s.id , h.id
    FROM `homework` CROSS JOIN  `students`
    WHERE h.id =  1
    

    A better approach woudl to be add all new columns that not exist in the table before, so you can run it every time you insert new rows in hmework

    INSERT INTO `teach_board` (`student_id`,`homework_id`)
    SELECT s.`id` , h.id
    FROM `homework` CROSS JOIN `students`
    WHERE NOt EXISTS ( SELECT 1 FROM  `teach_board` WHERE  `student_id` = s.id AND `homework_id` = h.id)