我有两张表格如下:
首先是Product
第二个是Documents
我只想要Product
表的每个记录的文档计数,但它只给出一行。我使用了以下查询:
SELECT `p`.`Id`,
`p`.`Name`,
`u`.`FirstName`,
`u`.`LastName`,
Count(doc.Id) AS NumOfDocuments
FROM (`Product` AS p)
LEFT JOIN `Documents` AS doc ON `p`.`Id` = `doc`.`ProductId`
INNER JOIN `ProductXUsers` AS pu ON `pu`.`ProductId` = `p`.`Id`
INNER JOIN `Users` AS u ON `u`.`Id` = `pu`.`UserId`
AND u.UserType='Customer'
WHERE `p`.`CreatedBy` = '3'
GROUP BY p.Id
答案 0 :(得分:0)
在您的查询中添加GROUP BY
,您只需删除包含 Product AS p
的括号:
SELECT `p`.`Id`,
`p`.`Name`,
`u`.`FirstName`,
`u`.`LastName`,
Count(doc.Id) AS NumOfDocuments
FROM `Product` AS p
LEFT JOIN `Documents` AS doc ON `p`.`Id` = `doc`.`ProductId`
INNER JOIN `ProductXUsers` AS pu ON `pu`.`ProductId` = `p`.`Id`
INNER JOIN `Users` AS u ON `u`.`Id` = `pu`.`UserId`
AND u.UserType='Customer'
WHERE `p`.`CreatedBy` = '3'
GROUP BY p.Id,`p`.`Name`,`u`.`FirstName`,`u`.`LastName`
答案 1 :(得分:0)
您忘记添加GROUP BY
子句。
此外,您可以使用IFNULL
替换null
值。
SELECT `p`.`Id`,
`p`.`Name`,
`u`.`FirstName`,
`u`.`LastName`,
IFNULL(Count(doc.Id),0) AS NumOfDocuments
FROM `Product` AS p
INNER JOIN `ProductXUsers` AS pu ON `pu`.`ProductId` = `p`.`Id`
INNER JOIN `Users` AS u ON `u`.`Id` = `pu`.`UserId` AND u.UserType='Customer'
LEFT JOIN `Documents` AS doc ON `p`.`Id` = `doc`.`ProductId`
WHERE `p`.`CreatedBy` = '3'
GROUP BY p.Id