Mysql错误:子查询返回超过1行

时间:2012-03-15 05:20:05

标签: mysql

您好我有一个mysql查询来获取一些id(studentID),如下所示

select t1.studentID 
from remittedfees t1 
where (select t2.fees 
       from feesasigned t2 
       where t2.studentID=t1.studentID) = (select sum(t3.remittedAmt) 
                                           from remittedfees t3 
                                           where t3.studentID = t1.studentID);

但查询返回以下错误

  ERROR 1242 (21000): Subquery returns more than 1 row

如何重写查询以获得结果?

4 个答案:

答案 0 :(得分:1)

试试这[更新]:

SELECT t2.studentID 
  from feesasigned t2 
  INNER JOIN (
  SELECT t3.studentID, SUM(t3.remittedAmt) FeeSum
  FROM remittedfees t3 
  GROUP BY t3.studentID) v ON t2.studentID = v.studentID and t2.fees = v.FeeSum

答案 1 :(得分:0)

select t2.fees查询很可能就像错误所说的那样 - 返回多行。在进行这样的相等比较时,=的两边都必须是单值。如果一方返回2+值,那么你最终会得到

1 = 1
2
3
好吧......什么是平等的? 1 = 1? 2 = 1? 3 = 1?比较的结果应该使用哪个单一的“真值”值?

答案 2 :(得分:0)

我想您要检索StudentID fees来自feesasigned表等于remittedAmtremittedfees的{​​{1}}。然后试试这个:

SELECT  a.studentID, b.fees, SUM(a.remittedAmt) TotalFees
FROM    remittedfees a INNER JOIN feesasigned b
            on a.studentID = b.studentID
GROUP BY a.studentID, b.fees
HAVING b.fees = SUM(a.remittedAmt)

答案 3 :(得分:0)

也许您正在寻找:

SELECT t2.studentID FROM feesasigned t2 
INNER JOIN 
    (select sum(t3.remittedAmt) as remitted_total, t3.studentID from remittedfees t3 
     GROUP BY t3.studentID) t4
ON
    t2.fees = t4.remitted_total AND t2.studentId = t4.studentID

返回已支付所有费用的学生的身份证件

相关问题