2015-02-24 3 views
0

я могу вполне счастливо запустить этот код с одним отсчетом в нем:Несколько счетчиков в одном запросе с левыми соединениями - что группе?

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 | [email protected] | 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 | [email protected] | admin  | 
|   1 |   0 | [email protected] | supervisor | 
+--------------+--------------+-------------------+------------+ 

Это то, что я ожидал:

+--------------+--------------+-------------------+------------+ 
| checkincount | reprintcount |  email  | type | 
+--------------+--------------+-------------------+------------+ 
|   4 |   8 | [email protected] | admin  | 
|   1 |   0 | [email protected] | supervisor | 
+--------------+--------------+-------------------+------------+ 

Любое направление на то, что я делаю неправильно было бы оценено. Я мог бы, конечно, сделать это два отдельных запроса, но я стараюсь избегать этого, поэтому страница будет загружаться быстрее, и я предполагаю, что это можно сделать в одном запросе? Благодаря!

+0

граф попробовать (отличный ...) - хотя подзапросов или производной таблицы, вероятно, будет быстрее – FuzzyTree

ответ

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' 
+1

У меня нет никакой информации о структуре, но да, вы правы, мы можем удалить, что группа – Alex

+0

Большое спасибо за ваш ответ @Alex - Я вижу, что я сейчас делаю неправильно! – haakym