1242 - 子查询在子查询中返回多于一行

时间:2012-11-25 17:51:44

标签: mysql sql

我正在努力获得每位员工的待处理总额。以下查询工作正常:

SELECT SUM(amount) 
FROM pending
WHERE MONTH < DATE_SUB(curdate() , INTERVAL 1 MONTH) 
GROUP BY class

但是当我尝试将其添加为子查询时,它会给出以下错误:

  

1242 - 子查询返回超过1行

SELECT
  (period_diff(date_format(now(), '%Y%m'),
     date_format(MONTH, '%Y%m'))) AS months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.name,
  staff.class, (
    SELECT SUM(amount) 
    FROM pending
    WHERE MONTH < DATE_SUB(curdate(), INTERVAL 1 MONTH) 
    GROUP BY class
  )
FROM
  pending JOIN staff
  ON pending.admission_numb = staff.admission
GROUP BY admission
ORDER BY CAST( staff.class AS UNSIGNED ) , staff.class

任何帮助将不胜感激..

2 个答案:

答案 0 :(得分:1)

由于您的子查询返回多行(我希望它会为每个类返回一行),您需要在from子句中加入子查询:

SELECT
  (period_diff(date_format(now(), '%Y%m'), date_format(MONTH, '%Y%m'))) AS months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.name,
  staff.class,
  sums.tot
FROM
  pending JOIN staff ON pending.admission_numb = staff.admission
  JOIN  (
    SELECT class, SUM(amount) as tot 
    FROM pending
    WHERE MONTH < DATE_SUB(curdate(), INTERVAL 1 MONTH)
    GROUP BY class
  ) sums on staff.class = sums.class
GROUP BY admission
ORDER BY CAST( staff.class AS UNSIGNED ) , staff.class

答案 1 :(得分:0)

这很简单,真的。子查询只能返回一行。这就是错误消息告诉你的内容。您提供的查询最有可能返回多行(实际上每个类一个)。由于你没有提供输出,我只能猜测这是真的。

要修复它,您需要更改该查询以返回一行。也许你摆脱了GROUP BY,或者你可能选择最大(或最小)的总和并返回它。这取决于您的业务需求。