Vijay Vj
Vijay Vj

Reputation: 67

SQL Query - Subquery returns more than one row

Table:

laterecords
-----------
studentid - varchar
latetime - datetime
reason - varchar

My Query:

SELECT laterecords.studentid,
laterecords.latetime,
laterecords.reason,
( SELECT Count(laterecords.studentid) FROM laterecords 
      GROUP BY laterecords.studentid ) AS late_count 
FROM laterecords

I'm getting " MySQL Subquery Returns more than one row" error.

I know a workaround for this query to use the following query:

SELECT laterecords.studentid,
laterecords.latetime,
laterecords.reason 
FROM laterecords

Then using php loop to though the results and do below query to get the late_count and echo it out:

SELECT Count(laterecords.studentid) AS late_count FROM laterecords 

But i think there might be a better solution ?

Upvotes: 3

Views: 2549

Answers (1)

Mark Byers
Mark Byers

Reputation: 838896

The simple fix is to add a WHERE clause in your subquery:

SELECT
    studentid,
    latetime,
    reason,
    (SELECT COUNT(*)
     FROM laterecords AS B
     WHERE A.studentid = B.student.id) AS late_count 
FROM laterecords AS A

A better option (in terms of performance) is to use a join:

SELECT
    A.studentid,
    A.latetime,
    A.reason,
    B.total
FROM laterecords AS A
JOIN 
(
    SELECT studentid, COUNT(*) AS total
    FROM laterecords 
    GROUP BY studentid
) AS B
ON A.studentid = B.studentid

Upvotes: 3

Related Questions