我的查询是:
SELECT business.name, AVG(rating.value) as total
FROM business
INNER JOIN rating
ON business.id = rating.business_id
INNER JOIN directory
ON business.id = directory.item_id
WHERE directory.directory_id = 13
AND directory.type = 'business'
AND rating.rating_id = '1'
GROUP BY business.id
ORDER BY total DESC
我的问题是,我想包括任何商家,即使他们没有与之相关的任何评级?
答案 0 :(得分:2)
您需要使用LEFT JOIN
代替INNER JOIN
:
SELECT business.name, AVG(rating.value) as total
FROM business
INNER JOIN directory
ON business.id = directory.item_id
LEFT JOIN rating
ON business.id = rating.business_id AND rating.rating_id = '1'
WHERE directory.directory_id = 13
AND directory.type = 'business'
GROUP BY business.id
ORDER BY total DESC
如果没有评级,则总计将为NULL。 您可以在MySQL(如果需要)中处理此问题:
IFNULL(AVG(rating.value), 'No ratings') as total
另请注意,您需要将rating.rating_id = '1'
移至JOIN条件。
答案 1 :(得分:0)
加入LEFT JOIN
- 表时,请执行INNER JOIN
而不是rating
。
答案 2 :(得分:0)
你只需要改变......
INNER JOIN rating
到
LEFT JOIN rating
INNER JOIN返回两个表中都匹配的行。
答案 3 :(得分:0)
在加入商家和评分时,将INNER JOIN
更改为LEFT JOIN
答案 4 :(得分:-1)
您想要LEFT OUTER JOIN。
SELECT business.name, AVG(rating.value) as total
FROM business
LEFT OUTER JOIN rating
ON business.id = rating.business_id
INNER JOIN directory
ON business.id = directory.item_id
WHERE directory.directory_id = 13
AND directory.type = 'business'
AND rating.rating_id = '1'
GROUP BY business.id
ORDER BY total DESC