通过subQuery进行多行插入

时间:2014-02-07 08:02:53

标签: mysql subquery bulkinsert multiple-records

我正在尝试使用子查询插入多行,但它给出了错误“SubQuery返回超过1行”

场景是我想针对子部门的每个测试添加注释,我通过子查询得到所有测试ID但是我无法迭代id并且针对每个测试插入注释。这是我的SQL查询

INSERT INTO dc_tp_comment  (labid,branchid,Comment,testid,lastupdated,enteredby)
Values('abcd',101,'comment here',(select T.testid
from dc_tp_test T
Inner Join dc_tp_subdepartments S
on T.subdepartmentid = S.subdepartmentid
Where S.subdepartmentid = 13),sysdate(),1)

2 个答案:

答案 0 :(得分:3)

您不能在一列中使用subselect,将它们用于整行:

INSERT INTO dc_tp_comment  (labid,branchid,Comment,testid,lastupdated,enteredby)
select 'abcd',101,'comment here', T.testid, sysdate() , 1
from dc_tp_test T Inner Join dc_tp_subdepartments S
on T.subdepartmentid = S.subdepartmentid
Where S.subdepartmentid = 13

答案 1 :(得分:0)

如果要插入多行,请使用select而不是值... 语法如下:

INSERT INTO dc_tp_comment  (labid,branchid,Comment,testid,lastupdated,enteredby)
select 'abcd',101,'comment here',(select T.testid
from dc_tp_test T
Inner Join dc_tp_subdepartments S
on T.subdepartmentid = S.subdepartmentid
Where S.subdepartmentid = 13),sysdate(),1