我正在尝试按其状态对帖子进行计数。但是下面的查询给我这个错误。
错误消息:[42000] [1140]在没有GROUP BY的汇总查询中, SELECT列表的表达式#1包含未聚合的列 'jquzntys.posts.id';这与 sql_mode = only_full_group_by
SELECT COUNT(p.id) total,
p1.authors authors,
p2.published published,
p3.pending pending,
p4.scheduled scheduled,
p5.draft draft,
p6.deleted deleted
FROM posts p
LEFT JOIN (
SELECT id, COUNT(*) as `authors`
FROM posts
WHERE user_id = ?
) AS p1 ON p1.id = p.id
LEFT JOIN (
SELECT id, COUNT(*) as `published`
FROM posts
WHERE status = ?
) AS p2 ON p2.id = p.id
LEFT JOIN (
SELECT id, COUNT(*) as `pending`
FROM posts
WHERE status = ?
) AS p3 ON p3.id = p.id
LEFT JOIN (
SELECT id, COUNT(*) as `scheduled`
FROM posts
WHERE status = ?
) AS p4 ON p4.id = p.id
LEFT JOIN (
SELECT id, COUNT(*) as `draft`
FROM posts
WHERE status = ?
) AS p5 ON p5.id = p.id
LEFT JOIN (
SELECT id, COUNT(*) as `deleted`
FROM posts
WHERE status = ?
) AS p6 ON p6.id = p.id
没有需要分组的数据。为什么我会收到此错误?
答案 0 :(得分:1)
嗯。 。 。这行得通,对我来说很有意义:
SELECT p.id, COUNT(*) as num_posts,
p1.authors authors,
p2.published published,
p3.pending pending,
p4.scheduled scheduled,
p5.draft draft,
p6.deleted deleted
FROM posts p . . .
GROUP BY p.id, p1.authors, p2.published, p3.pending, p4.scheduled, p5.draft, p6.deleted
但是,我想我会像其他人一样将聚合纳入其中:
SELECT p.id, p.num_posts,
p1.authors authors,
p2.published published,
p3.pending pending,
p4.scheduled scheduled,
p5.draft draft,
p6.deleted deleted
FROM (SELECT p.id, COUNT(*) as cnt
FROM posts p
GROUP BY p.id
) p LEFT JOIN
. . .
话说回来,这似乎很奇怪。 id
在posts
中不是唯一的吗?
编辑:
或者,我认为这可能是您真正想要的:
SELECT COUNT(*) as num_posts,
SUM(p1.authors) as authors,
SUM(p2.published) as published,
SUM(p3.pending) as pending,
SUM(p4.scheduled) as scheduled,
SUM(p5.draft) as draft,
SUM(p6.deleted) as deleted
FROM posts p . . .
答案 1 :(得分:1)
如果您使用COUNT()
,但未指定GROUP BY
子句,则该子句仍符合汇总查询的条件,但整个结果将被视为一个“组”。您可能会认为您没有分组,因为您没有GROUP BY
子句,但是在使用COUNT()
时它是隐式的。
似乎您想统计每种状态的帖子数,并显示(任何状态的)帖子总数,还显示特定用户的帖子数。
我建议通过两个独立的查询来做到这一点:
SELECT COUNT(*) as count
FROM posts
WHERE user_id = ?;
SELECT status, COUNT(*) as count
FROM posts
GROUP BY status WITH ROLLUP;
第二个查询的优点是,如果将来有任何新的状态值出现,则不必重写查询。 WITH ROLLUP
为您提供结果集最后一行的总数(在该行上,status
为NULL)。
并非每个任务都需要在单个SQL查询中实现。有时将查询分为两个查询可以使两个查询更加简单明了。