How to use 'select ' in MySQL 'insert&

2019-01-14 17:39发布

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

Structure of b.students table is rollno, ssn, name.

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

2条回答
Juvenile、少年°
2楼-- · 2019-01-14 17:58
INSERT INTO a.grades (rollno, grade)
    SELECT rollno, 'A' FROM b.students WHERE ssn = 12345;

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');
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-14 18:12

Columns in insert into and select must be equal

insert into grades (field1, field2)
select field1,field2 from students where ssn=12345;
查看更多
登录 后发表回答