0

我有这样的查询:

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) as comments_count,,我返回了 2 行。当它存在时,只返回 1 行。

有什么方法可以解决 ot 或者我只需要更改 count(c.id) as comments_count,(select count(id) ascomments_countfrom blog_comments where note = b.id) as comments_count,吗?

4

1 回答 1

3

Count(*)是一个聚合函数,因此它将应用于一个组。这意味着当您依靠组时,它将将该功能应用于每个组。这些组是在您使用 Group By 时形成的,在这种情况下,您没有使用,因此MySQL请考虑所有选择(您的加入)只有 1 个 GROUP。

因此,将计数应用于唯一组并返回行数。

Group by你应该在你想要的字段中添加一个

一个例子是here

于 2012-08-30T12:10:30.907 回答