我有这样的查询:
SELECT
b.title,
b.url,
b.`date`,
b.gallery,
count(c.id) as comments_count,
a.name,
b.content,
b.comments,
LEFT(b.content, LOCATE('<page>', b.content)-1) as content_short
FROM blog b
LEFT JOIN blog_comments c ON
(b.id = c.note AND c.approved = 1)
LEFT JOIN administrators a ON
(b.aid = a.id)
WHERE
b.`date` < now() AND
b.active = 1
ORDER BY b.`date` DESC;
现在,当我删除 count(c.id) 作为 comments_count,
时,我返回了 2 行。当它存在时,仅返回 1 行。
有什么方法可以解决这个问题,或者我只需要改变
count(c.id) as comments_count,
到 (select count(id) as
comments_countfrom blog_comments where note = b.id) as comments_count,
?
最佳答案
Count(*)
是一个聚合函数,因此它将应用于组中。
这意味着当您依赖组时,它将将该函数应用于每个组。
这些组是在您使用 Group By 时形成的,在本例中,您没有使用,因此 MySQL
认为 ALL select(您的联接)是ONLY 1 GROUP。
因此,将计数应用于唯一组并返回行数。
您应该在您想要的字段旁边添加一个分组依据
一个例子是 here
关于mysql - 连接表计数导致返回 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12196510/