sql error(1242):子查询返回多行

时间:2012-11-07 05:28:35

标签: mysql sql

我有两张表a_dailyo_daily_lcsgeneration

我正在尝试此查询:

update a_daily
set
  a_daily.Turbine_Generation =  
   (
     select sum(o_daily_lcsgeneration.Turbine_Generation) 
     from o_daily_lcsgeneration 
     where o_daily_lcsgeneration.Location = 1 
     group by o_daily_lcsgeneration.Date
  ) 

但收到上述错误,说子查询超过1行

3 个答案:

答案 0 :(得分:3)

删除GROUP BY子句

UPDATE a_daily
SET a_daily.Turbine_Generation = 
(
        SELECT sum(o_daily_lcsgeneration.Turbine_Generation)
        FROM o_daily_lcsgeneration
        WHERE o_daily_lcsgeneration.Location = 1
)

它会导致查询返回多个日期的多个值。

更新1

UPDATE  a_daily a
        INNER JOIN
        (
            select g.Date, sum(g.Turbine_Generation) totalSum
            from o_daily_lcsgeneration g
            where g.Location = 1 
            group by g.Date
        ) b ON a.date = b.date
SET     a.Turbine_Generation = b.totalSum
WHERE       a.location = 1

UPDATE  a_daily a
        LEFT JOIN JOIN
        (
            select g.Date, sum(g.Turbine_Generation) totalSum
            from o_daily_lcsgeneration g
            where g.Location = 1 
            group by g.Date
        ) b ON a.date = b.date
SET     a.Turbine_Generation = COALESCE(b.totalSum, 0)

答案 1 :(得分:1)

运行子查询,您将看到它返回多行。您按日期对结果进行分组,因此SUM表达式计算每天的值。您可以重新编写查询,如下所示:

UPDATE a_daily
SET a_daily.Turbine_Generation = (SELECT SUM(o_daily_lcsgeneration.Turbine_Generation) 
                                    FROM o_daily_lcsgeneration 
                                   WHERE o_daily_lcsgeneration.Location = 1 
                                     AND o_daily_lcsgeneration.Date = 'YYYY-MM-DD'
                                GROUP BY o_daily_lcsgeneration.Date)

或(所有事件的总和):

UPDATE a_daily
SET a_daily.Turbine_Generation = (SELECT SUM(o_daily_lcsgeneration.Turbine_Generation) 
                                    FROM o_daily_lcsgeneration 
                                   WHERE o_daily_lcsgeneration.Location = 1)

答案 2 :(得分:1)

update a_daily
set
  a_daily.Turbine_Generation =  (
     select sum(o_daily_lcsgeneration.Turbine_Generation) 
     from o_daily_lcsgeneration where o_daily_lcsgeneration.Location = a_daily.Location  
     group by o_daily_lcsgeneration.Date
  )