sql中的insert语句中的select语句返回多行

时间:2016-03-16 08:33:37

标签: mysql sql

我在mysql中有一个以下结构化查询。但它返回了一个错误。基本上,我想从现有的表和instert到新表获得价值。我尝试了以下方法,但收到了错误;

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。问题是我从select内的insert查询获得的不仅仅是单个记录。如何删除此类错误。

1 个答案:

答案 0 :(得分:2)

总查询类似于下面的内容。你在哪里用你想要选择的列名替换*!

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
)

我感动了您将选择语句放入子查询中,这样您就可以使用子查询的总结果来获得优势。