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 aGROUP BYclause, and MySQL is lenient about the presence or contents of theGROUP 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 toGROUP BY Users.GUIDwithout the subquery, which is simpler, you may not get the results you expect fromUsers.NameorUsers.CreationDate. This method is more portable: