我可以很高兴地运行这段代码,其中包含一个计数:
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、reprrin`.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 |
+--------------+--------------+-------------------+------------+
任何有关我做错的事情的指示将不胜感激。我当然可以这样做,这是两个单独的查询,但我试图避免这种情况,这样页面加载速度会更快,我猜这可以在一个查询中完成?谢谢!
最佳答案
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'
关于mysql - 带有左连接的一个查询中的多个计数 - 按什么分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28700370/