sql中的insert语句中的select语句返回多行
Posted
技术标签:
【中文标题】sql中的insert语句中的select语句返回多行【英文标题】:select statement inside insert statement in sql returns multiple rows 【发布时间】:2016-07-02 00:28:15 【问题描述】:我在 mysql 中有以下结构化查询。但它返回一个错误。基本上,我想从现有表中获取价值并插入新表。我尝试了以下方法,但出现错误;
INSERT INTO `table1`(
`first`,`second`,`third`) VALUES(
(SELECT table2.timemodified FROM `xtable` AS table2,`ytable` AS table3
WHERE table3.id = table2.contextid),
(SELECT table4.id FROM `ztable` AS table4,`ytable` AS table3 WHERE table4.id = table3.instanceid),
(SELECT murs.id FROM `table5` AS murs,
`xtable` AS table2,
`wtable` AS table6,
`ytable` AS table3,
`vtable` AS table7
WHERE murs.id = table2.userid AND table6.id = table2.roleid AND table3.id = table2.contextid AND table7.instance = table3.instanceid AND table6.id =3)
);
我测试过,但错误是:#1242 - Subquery returns more than 1 row
。问题是我从insert
内的select
查询中获得的不仅仅是一条记录。如何消除此类错误。
【问题讨论】:
您要插入多行吗?只插入一行。 是的,我想插入多行 然后使用:插入表 (value1, value2, value3) select x,y,z from table2 我没听懂你,请你详细说明你的答案:) 我猜您的子查询(select
查询)返回的行不止一行。我建议尝试在每个select
查询中添加limit 1
,然后尝试一次,如果一切正常,那么查询是正确的,您需要找到一种方法来限制返回的行。
【参考方案1】:
总查询如下所示。用您要选择的列名替换 * !
INSERT INTO table1(first,second,third)
-- replace * with columns name first,second,third
select * from (
-- START YOU'RE select query
(SELECT table2.timemodified FROM `xtable` AS table2,`ytable` AS table3
WHERE table3.id = table2.contextid),
(SELECT table4.id FROM `ztable` AS table4,`ytable` AS table3 WHERE table4.id = table3.instanceid),
(SELECT murs.id FROM `table5` AS murs,
`xtable` AS table2,
`wtable` AS table6,
`ytable` AS table3,
`vtable` AS table7
WHERE murs.id = table2.userid AND table6.id = table2.roleid AND table3.id = table2.contextid AND table7.instance = table3.instanceid AND table6.id =3)
-- END YOU'RE select query
)
我将您的 select 语句移到子查询中,这样您就可以使用子查询的总结果来获得优势。
【讨论】:
你能解释一下吗:)以上是关于sql中的insert语句中的select语句返回多行的主要内容,如果未能解决你的问题,请参考以下文章
如何将sqlserver表中的数据导出sql语句或生成insert into语句