您可以插入一个 table 中,其中一个值是 mysql 中声明的变量吗?

Can you insert into a table where a value is a declared variable in mysql?

是否可以这样做?

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(teacherId, "12A1", "trig", "tomorrow")
teacherID = (
        SELECT teacherId
        FROM teacherlogins
        WHERE teacherid = 5
    )

我知道这个查询是不正确的,但是否可以用另一种方式进行查询?

有几种方法可以做到这一点。一个是芭芭拉在上面的评论中,使用 INSERT...SELECT syntax:

INSERT INTO homework(teacherId, class, name, dueDate)
SELECT teacherId, '12A1', 'trig', 'tomorrow'
FROM teacherlogins
WHERE teacherid = 5;

这是另一个使用 scalar subquery operand:

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES((SELECT teacherId FROM teacherlogins WHERE teacherid = 5 LIMIT 1),
    '12A1', 'trig', 'tomorrow')

这是另一个使用 user-defined variable and SELECT INTO syntax:

SELECT teacherId INTO @t FROM teacherlogins WHERE teacherid = 5;

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(@t, '12A1', 'trig', 'tomorrow');

这是另一个::-)

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(5, '12A1', 'trig', 'tomorrow');