3

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"
4

1 回答 1

2

问题是您使用的是聚合函数(AVG)。即使没有实际匹配的行,这将为您提供单行(在没有 GROUP BY 子句的情况下)。

试试这个:-

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
于 2013-06-26T13:06:49.393 回答