如果没有结果,此查询将返回包含所有NULL
值的1条记录。如果应该有结果似乎返回正常。
我使用内部联接使用表主键获取一些帐户详细信息和评级。一些非主要(多对一)键的默认值为NULL - 这可能导致它以某种方式加入自身?
为什么它返回一个包含所有空值的行?
SELECT a.account_id, a.first_name, a.second_name, a.points, c.body, c.creation_time, AVG(t.rating_overall)
FROM comments AS c
INNER JOIN accounts AS a
ON c.account_id=a.account_id
INNER JOIN ratings AS t
ON t.blogger_id=a.account_id
WHERE c.blog_id = ?
ORDER BY c.creation_time ASC"
答案 0 :(得分:2)
问题是您正在使用聚合函数(AVG)。这将给你一行(在GROUP BY子句的abscence中),即使没有实际匹配的行。
试试这个: -
SELECT a.account_id, a.first_name, a.second_name, a.points, c.body, c.creation_time, AVG(t.rating_overall)
FROM comments AS c
INNER JOIN accounts AS a
ON c.account_id=a.account_id
INNER JOIN ratings AS t
ON t.blogger_id=a.account_id
WHERE c.blog_id = ?
GROUP BY a.account_id, a.first_name, a.second_name, a.points, c.body, c.creation_time
ORDER BY c.creation_time ASC