1
我有3個表格:照片,用戶,投票。 我想用的用戶名和投票的所有照片:MySQL JOIN空表只返回一行
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`
數據:
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 |
---------------------------
上面的查詢將返回唯一一個一行,當沒有票:
Photo | Name | Surname | Votes
-------------------------------------
pic1.jpg | User1 | Sur1 | 0
-------------------------------------
但我想得到所有三行(所有三e照片):
-------------------------------------
Photo | Name | Surname | Votes
-------------------------------------
pic1.jpg | User1 | Sur1 | 0
-------------------------------------
pic2.jpg | User2 | Sur2 | 0
-------------------------------------
pic3.jpg | User3 | Sur3 | 0
-------------------------------------
解決:GROUP BY子句應該是f
。 Id
,而不是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.Show'在那裏顯着嗎? –
爲了放大@ Ray的評論,如果只有一個照片行的f.show爲1,那麼你只會得到一行。 –
感謝您的回覆,但我在GROUP BY子句中犯了一個錯誤。 –