Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql LEFT Join query only returns one row when adding Count() mysql function

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

like image 284
TheDude Avatar asked Dec 18 '25 00:12

TheDude


2 Answers

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
like image 163
Michael Berkowski Avatar answered Dec 20 '25 19:12

Michael Berkowski


You need to group by user, otherwise it collapses all to one row: GROUP BY Users.GUID

like image 30
sashkello Avatar answered Dec 20 '25 17:12

sashkello