使用左连接的一个查询中的多个计数 - 要分组的内容?

时间:2015-02-24 15:55:37

标签: mysql sql count

我可以很高兴地运行这个代码,其中有一个计数:

select 
  count(`reprint`.`user_id`) as `reprintcount`, 
  `users`.`email` as `email`,
  `users`.`type` as `type`
from `users`
left join `reprint`
  on `users`.`id` = `reprint`.`user_id`
where `users`.`type` = 'assistant' 
  or `users`.`type` = 'admin' 
  or `users`.`type` = 'supervisor'
group by `users`.`id`

我会得到这样的东西:

+--------------+-------------------+------------+
| reprintcount |       email       |    type    |
+--------------+-------------------+------------+
|            8 | user1@example.org | admin      |
|            0 | user2example.org  | supervisor |
+--------------+-------------------+------------+

但是当我通过左连接添加另一个表并抛出另一个计数时,我开始遇到问题。

select 
  count(`checkin`.`user_id`) as `printcount`, 
  count(`reprint`.`user_id`) as `reprint`, 
  `users`.`email` as `email`,
  `users`.`type` as `type`
from `users` 
left join `checkin` 
  on `users`.`id` = `checkin`.`user_id`
left join `reprint`
  on `users`.`id` = `reprint`.`user_id`
where `users`.`type` = 'assistant' 
  or `users`.`type` = 'admin' 
  or `users`.`type` = 'supervisor'
group by `users`.`id`

我得到的问题是,我从计数中得到了意想不到的数字。我尝试过user.id,checkin.user_id,reprin`.user_id或三者的混合,但无济于事。这就是我得到的:

+--------------+--------------+-------------------+------------+
| checkincount | reprintcount |       email       |    type    |
+--------------+--------------+-------------------+------------+
|           32 |           32 | user1@example.org | admin      |
|            1 |            0 | user2@example.org | supervisor |
+--------------+--------------+-------------------+------------+

这就是我所期待的:

+--------------+--------------+-------------------+------------+
| checkincount | reprintcount |       email       |    type    |
+--------------+--------------+-------------------+------------+
|            4 |            8 | user1@example.org | admin      |
|            1 |            0 | user2@example.org | supervisor |
+--------------+--------------+-------------------+------------+

任何关于我做错事的方向都会受到赞赏。我当然可以这是两个单独的查询,但我试图避免这样,所以页面加载速度更快,我猜这可以在一个查询中完成?谢谢!

1 个答案:

答案 0 :(得分:1)

select 
  c.`printcount`, 
  r.`reprint`, 
  `users`.`email` as `email`,
  `users`.`type` as `type`
from `users` 
left join (
   select `user_id`, count(*) as `printcount`
   from `checkin` 
   group by `user_id`
) as c
  on `users`.`id` = c.`user_id`
left join (
   select `user_id`, count(*) as `reprint`
   from `reprint` 
   group by `user_id`
) as r
  on `users`.`id` = r.`user_id`
where `users`.`type` = 'assistant' 
  or `users`.`type` = 'admin' 
  or `users`.`type` = 'supervisor'