I have 3 tables: photos, users, votes. I want to get all photos with usernames and votes:
SELECT
`f`.`Photo`,
`u`.`Name`,
`u`.`Surname`,
COUNT(`h`.`Id`) AS `Votes`
FROM
`photos` `f`
JOIN
`users` `u`
ON
`f`.`UserId` = `u`.`Id`
LEFT JOIN
`votes` `h`
ON
`f`.`Id` = `h`.`PhotoId`
WHERE
`f`.`Show` = '1'
GROUP BY
`h`.`PhotoId`
Data:
photos:
---------------------------
|Id | Photo | UserId |
---------------------------
|1 | pic1.jpg | 1 |
---------------------------
|2 | pic2.jpg | 2 |
---------------------------
|3 | pic3.jpg | 3 |
---------------------------
users:
---------------------------
|Id | Name | Surname|
---------------------------
|1 | User1 | Sur1 |
---------------------------
|2 | User2 | Sur2 |
---------------------------
|3 | User3 | Sur3 |
---------------------------
votes (is empty):
---------------------------
|Id | PhotoId | Date |
---------------------------
The query above will return only one row, when there are no votes:
Photo | Name | Surname | Votes
-------------------------------------
pic1.jpg | User1 | Sur1 | 0
-------------------------------------
but I'd like to get all three rows (for all three photos):
-------------------------------------
Photo | Name | Surname | Votes
-------------------------------------
pic1.jpg | User1 | Sur1 | 0
-------------------------------------
pic2.jpg | User2 | Sur2 | 0
-------------------------------------
pic3.jpg | User3 | Sur3 | 0
-------------------------------------
SOLVED: The GROUP BY clause should be f.Id, not h.PhotoId:
SELECT
`f`.`Photo`,
`u`.`Name`,
`u`.`Surname`,
COUNT(`h`.`Id`) AS `Votes`
FROM
`photos` `f`
JOIN
`users` `u`
ON
`f`.`UserId` = `u`.`Id`
LEFT JOIN
`votes` `h`
ON
`f`.`Id` = `h`.`PhotoId`
WHERE
`f`.`Show` = '1'
GROUP BY
`f`.`Id`
f.Showin there significant?f.showis1for only one photo row, then you'll get only one row back.