如何在联结表上插入值

时间:2019-03-23 01:26:38

标签: mysql sql database vb.net phpmyadmin

嗨,我无法在联结表上插入数据。

我的更新查询工作正常

sql = "UPDATE student_subject " & _
            " INNER JOIN subject_bsit " & _
            " ON subject_bsit.subject_id = student_subject.sub_id " & _
            " SET grade = "1" where student_subject.student_id= "1235" AND student_subject.sub_id = 1"

这是我在联结表中插入数据的SQL语句,我做错了什么原因导致语法错误

sql = "INSERT INTO student_subject (student_id,sub_id,grade) " & _
            " INNER JOIN student " & _
            " ON student.StudentID = student_subject.student_id " & _
            " VALUES ("1235","4","1.25")" & _
            " where student_subject.student_id= "1235""

我想做的是让 studentID 1235 拥有一个 subject_id 4 ,它是网络。

这是我的数据库表

student Table

    -----------------------
    |studentID | FullName |
    -----------------------
    |1234      | John    |
    |1235      | Michael |
    |1236      | Bryce   |

"subject_bsit"

    -----------------------------------------
    |subject_id| subject_name  |  pre_id    |
    -----------------------------------------
    |    1     | Programming 1 |    NULL     |
    |    2     | Networking    |    NULL     |
    |    3     | Algorithm     |    NULL     |
    |    4     | Physical Educ |    NULL     |
    |    5     | Programming 2 |     1       |

This is the Junction table to connect the 
    two now.

"student_subject"

    -------------------------------------
    | student_id | subject_id | Grade   |
    -------------------------------------
    |   1235     |      1     |   NULL  |
    |   1235     |      2     |    2    |
    |   1235     |      3     |    1    |
    |   1234     |      1     |   2.25  |

1 个答案:

答案 0 :(得分:0)

由于语法错误,您使用了INSERT语句。

有关更多详细信息,请参见https://dev.mysql.com/doc/refman/8.0/en/insert.html

您可以在JOIN语句中使用UPDATE,因为它是[where_clause]参数的一部分。 (https://dev.mysql.com/doc/refman/8.0/en/update.html

您应该像下面那样使用INSERT INTO [table1] SELECT [column] FROM [table2]根据其他表中的值将值插入表中。

INSERT INTO student_subject (student_id,sub_id,grade) 
SELECT student.StudentId, 4, null
FROM student
WHERE student.studentID = 1235;

您可以在JOIN行之后的SELECT语句中添加特定的FROM student语句。

SQLFiddle