INSERT INTO(选择多列连接(具有更多连接,总和...),合并,月...)

时间:2014-05-27 22:31:08

标签: mysql sql

我的查询是:

INSERT into per_m (ANO,REM_I,QTD)
VALUES
(SELECT '2014-04-01' as ANO ,rem_i.ID as REM_I,

COALESCE(
        per_m.QTD-coalesce(rem_o.QTD+rem_intl.QTD,rem_o.QTD,rem_intl.QTD,0)
                  ,
        rem_i.QTD-coalesce(rem_o.QTD+rem_intl.QTD,rem_o.QTD,rem_intl.QTD,0)
         )as QTD


FROM rem_i 
left JOIN
incom on incom.ID=rem_i.INCOM
left JOIN
per_m on per_m.REM_I=rem_i.ID

left JOIN
(SELECT rem_o.REM_I, SUM(rem_o.QTD)as QTD from rem_o
LEFT JOIN outcom
ON (outcom.ID=rem_o.OUTCOM)
WHERE month(outcom.DATA)='03'
GROUP BY rem_o.REM_I)as rem_o

on(rem_o.REM_I=rem_i.ID )


left JOIN
(SELECT rem_intl.REM_I, SUM(rem_intl.QTD)as QTD from rem_intl
LEFT JOIN intl
ON (intl.ID=rem_intl.INTL)
WHERE month(intl.DATA)='03'
GROUP BY rem_intl.REM_I)as rem_intl

on(rem_intl.REM_I=rem_i.ID )


WHERE month(per_m.ANO)='03'or month(incom.DATA)='03'
GROUP BY REM_I)

并且错误在第3行:出现无效消息#1064。我只测试了选择,一切正常。我从不使用插入 SELECT。什么可能出错?

并且有人知道我可以模拟数据库接口的任何页面(比如jsfiddle),但有一些查询和表格用于共享一些我上面的查询测试的样本吗?

1 个答案:

答案 0 :(得分:2)

首先,正如@Strawberry正确指出的那样,使用SQL Fiddle构建样本。关于您的查询,请删除单词VALUES。正确的语法是:

INSERT INTO tablename (columns) SELECT samenumberofcolumns...

在您的情况下,这应该有效:

INSERT into per_m (ANO,REM_I,QTD)
SELECT '2014-04-01' as ANO ,rem_i.ID as REM_I,

COALESCE(
        per_m.QTD-coalesce(rem_o.QTD+rem_intl.QTD,rem_o.QTD,rem_intl.QTD,0)
                  ,
        rem_i.QTD-coalesce(rem_o.QTD+rem_intl.QTD,rem_o.QTD,rem_intl.QTD,0)
         )as QTD


FROM rem_i 
left JOIN
incom on incom.ID=rem_i.INCOM
left JOIN
per_m on per_m.REM_I=rem_i.ID

left JOIN
(SELECT rem_o.REM_I, SUM(rem_o.QTD)as QTD from rem_o
LEFT JOIN outcom
ON (outcom.ID=rem_o.OUTCOM)
WHERE month(outcom.DATA)='03'
GROUP BY rem_o.REM_I)as rem_o

on(rem_o.REM_I=rem_i.ID )


left JOIN
(SELECT rem_intl.REM_I, SUM(rem_intl.QTD)as QTD from rem_intl
LEFT JOIN intl
ON (intl.ID=rem_intl.INTL)
WHERE month(intl.DATA)='03'
GROUP BY rem_intl.REM_I)as rem_intl

on(rem_intl.REM_I=rem_i.ID )


WHERE month(per_m.ANO)='03'or month(incom.DATA)='03'
GROUP BY REM_I