I have this mysql query (evolving two tables: Users and Files) that's giving me headaches:
SELECT Users.GUID, Users.Name, Users.CreationDate, Files.Date,
Count(Files.GUID) As FilesCount
FROM Users
LEFT JOIN Files ON Users.GUID = Files.UserGUID
WHERE Users.Group = '1'
When I execute it, it always return 1 row (which is not what I want). But if I remove this:
Count(Files.Date) As FilesCount
It correctly return all the rows that I expect.
I basically need to get the number of files that belongs to a user (along with the user info)
My question is: How can I fix this & make the mysql query return the user basic info along with the files count?
BTW, I'm using CodeIgniter 2 with PHP 5 (although I don't think it matters here...)
The COUNT() aggregate will return only one row in absence of a GROUP BY clause, and MySQL is lenient about the presence or contents of the GROUP BY (your query would have failed with a syntax error in most other RDBMS).
Since you have multiple columns, you ought to join against a subquery to get the count per Files.GUID. Although MySQL will permit you to GROUP BY Users.GUID without the subquery, which is simpler, you may not get the results you expect from Users.Name or Users.CreationDate. This method is more portable:
SELECT
Users.GUID,
Users.Name,
Users.CreationDate,
FileCount
FROM
Users
/* Subquery returns UserGUID and associated file count */
LEFT JOIN (
SELECT UserGUID, COUNT(*) AS FileCount
FROM Files
GROUP BY UserGUID
) fc ON Users.GUID = fc.UserGuid
WHERE Users.Group = 1
You need to group by user, otherwise it collapses all to one row: GROUP BY Users.GUID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With