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

问题描述:

我正在尝试向表中插入其他行,该表要求从另一个表中检索一个值.以下是查询示例:

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');