MySQL多个COUNT组

时间:2009-06-15 23:20:33

标签: mysql propel

我有这个查询,但我不知道是否可以这样做。基本上,我正在按每列进行计数和分组。但是,我想显示计数DESC / ASC。由于它们是不同的列,我可以实现这一点吗?这是我的疑问:

SELECT flags.ID, flags.COMMENT_ID, flags.CONTENT_ID, flags.USER_ID, flags.WALLPOST_ID, flags.FLAGGED_BY, flags.DATE_FLAGGED, flags.PROD_ID, flags.STAGE_ID, COUNT(flags.COMMENT_ID) AS comment_count, COUNT(flags.CONTENT_ID) AS content_count, COUNT(flags.WALLPOST_ID) AS wall_count, COUNT(flags.USER_ID) AS user_count FROM flags LEFT JOIN comment ON (flags.COMMENT_ID=comment.ID) LEFT JOIN content ON (flags.CONTENT_ID=content.ID) LEFT JOIN sf_guard_user_profile ON (flags.USER_ID=sf_guard_user_profile.ID) LEFT JOIN wallpost ON (flags.WALLPOST_ID=wallpost.ID) GROUP BY flags.COMMENT_ID,flags.CONTENT_ID,flags.USER_ID,flags.WALLPOST_ID ORDER BY comment_count DESC,content_count DESC,wall_count DESC,user_count DESC LIMIT 1000

基本上,如果您查看下面的结果,我希望能够将计数分组到一个列中。这样,我可以轻松地进行分页和排序。

我是新的StackOverflow用户,所以我无法发布图片。以下是此链接:http://i40.tinypic.com/2wbvxci.jpg

提前致谢!

1 个答案:

答案 0 :(得分:2)

从那个jpg看,对于任何给定的行,只有一个计数将为非零,因此将SELECT更改为具有,而不是

COUNT(flags.COMMENT_ID) AS comment_count, COUNT(flags.CONTENT_ID) AS content_count, COUNT(flags.WALLPOST_ID) AS wall_count, COUNT(flags.USER_ID) AS user_count

部分,表达式如

(COUNT(flags.COMMENT_ID) + COUNT(flags.CONTENT_ID) + COUNT(flags.WALLPOST_ID) + COUNT(flags.USER_ID)) AS total_count

可能就是你想要的。