如何在 MySQL 'insert' 语句中使用 'select'

2022-01-09 00:00:00 select insert mysql

我正在尝试将其他行插入到需要从另一个表中检索值的表中.下面是一个示例查询:

I'm trying to insert additional rows into a table which requires a value to be retrieved from another table. Below is an example query:

insert into a.grades (rollno, grade)
values(select rollno from b.students where ssn=12345, 'A');

b.students表的结构是rollno, ssn, name.

我知道上面的查询是错误的.有没有办法在插入行时从其他表中检索 1 个值?

I knew the above query is wrong. Is there a way to retrieve 1 value from other table while inserting a row?

推荐答案

INSERT INTO a.grades (rollno, grade)
    SELECT rollno, 'A' FROM b.students WHERE ssn = 12345;

一些 DBMS 会接受以下内容,并在 SELECT 语句周围加上一组额外的括号:

Some DBMS would accept the following, with an extra set of parenthesis around the SELECT statement:

INSERT INTO a.grades (rollno, grade)
   VALUES((SELECT rollno FROM b.students WHERE ssn = 12345), 'A');

相关文章