简体   繁体   English

MySql查询结果中包含多个计数

[英]MySql query with multiple counts in result

I have a tables 我有一张桌子

create table posts (
   text varchar(20),
   created_at datetime,
   user_id integer
);

create table users (
   id integer,
   name varchar(20),
   important bolean
);

create table categories (
   id integer,
   name varchar(20),
);
create table categories_posts (
   category_id integer,
    post_id integer
);

Want to calculate the number of posts for each category between certain times with results like this 想要计算特定时间之间每个类别的帖子数量,结果如下

START_TIME_PERIOD, category, count_all, count_important, count_normal
'2013-03-06 23:40', 'dogs',    20,       5,               15
'2013-03-06 23:40', 'cats',    22,       6,               16
'2013-03-06 23:40', 'birds',   24,       7,               17

where the importance is based on the users importance. 其重要性取决于用户的重要性。

To get one count eg important 获得一个例如重要的计数

select '2013-03-06 23:40', categories.name, count(*)
from posts, users, categories
where posts.id = categories_posts.post_id
and categories.id = categories_posts.category_id
and posts.user_id = users.id
and users.important = true
and posts.created_at BETWEEN '2013-03-06 23:40' AND  '2013-03-06 23:20'
group by 1, 2

What is the best way to get the three counts in a single result set? 在单个结果集中获取三个计数的最佳方法是什么?

Thanks 谢谢

SELECT ..... , count(*), SUM(IF(user.important,1,0)) as count_important, COUNT(*) - SUM(IF(user.important,1,0)) as count_normal

Rather than using COUNT , you can use SUM combined with CASE , eg 您可以使用SUMCASE结合使用,而不是使用COUNT

SELECT COUNT(*) AS count_all, 
    SUM(CASE WHEN important = 1 THEN 1 ELSE 0 END) AS count_important

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM