ARUN P.S
ARUN P.S

Reputation: 1723

Mysql Error: Subquery returns more than 1 row

Hi I have a mysql query to fetch a number of id's(studentID), given below

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);

but the query returns the following error

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

How can I rewrite the query to get the result ?

Upvotes: 0

Views: 2342

Answers (4)

louis.luo
louis.luo

Reputation: 2971

Maybe you are looking for:

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

Which returns the IDs of the student who has paid all their fees

Upvotes: 0

John Woo
John Woo

Reputation: 263723

I think you want to retrieve StudentID whosefees from feesasigned table is queal to the total remittedAmt from remittedfees table. Then try this:

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)

Upvotes: 0

rs.
rs.

Reputation: 27427

Try this [updated]:

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

Upvotes: 1

Marc B
Marc B

Reputation: 360662

Most likely the select t2.fees query is doing just as the error says - returning more than one row. When doing an equality comparison like that, both sides of the = have to be single values. If one side returns 2+ values, then you end up with

1 = 1
2
3

ok... what's equal? 1=1? 2=1? 3=1? which single 'truth' value should be used as the result of the comparison?

Upvotes: 0

Related Questions