【问题标题】:How to insert value on junction table如何在联结表上插入值
【发布时间】:2019-03-23 01:26:37
【问题描述】:

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

我的更新查询运行良好

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  |

【问题讨论】:

    标签: mysql sql database vb.net phpmyadmin


    【解决方案1】:

    您有语法错误,因为您错误地使用了INSERT 语句。

    查看这里https://dev.mysql.com/doc/refman/8.0/en/insert.html了解更多详情。

    您可以在UPDATE 语句中使用JOIN,因为它是[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;
    

    您可以在SELECT 语句中为您的实际代码添加特定的JOIN 语句。

    SQLFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 2021-10-17
      • 1970-01-01
      相关资源
      最近更新 更多