| От | Tom Lane |
|---|---|
| Тема | Re: [SQL] Problems using count() with a join |
| Дата | |
| Msg-id | 7784.935068590@sss.pgh.pa.us обсуждение исходный текст |
| Ответ на | Problems using count() with a join (Doug Younger <postgres@mindspring.com>) |
| Список | pgsql-sql |
Doug Younger <postgres@mindspring.com> writes:
> What I want is to get a count of # of users in each group, even if there
> are no users in the group.
> I have tried the following:
> SELECT t1.g_name,count(t2.g_id)
> FROM groups t1,users t2
> WHERE t1.g_id = t2.g_id
> GROUP BY t1.g_name;
> But it only give the counts of users in each group if there actually are
> users in that group.
> I want the count to be 0 if there are no users in the group.
Try SELECT as above plus
... UNION SELECT t1.g_name, 0 FROM groups t1 WHERE NOT EXISTS(SELECT * FROM users t2 WHERE t1.g_id = t2.g_id);
Grotty, I know, but we don't have outer joins yet...
regards, tom lane
В списке pgsql-sql по дате отправления:
Сайт использует файлы cookie для корректной работы и повышения удобства. Нажимая кнопку «Принять» или продолжая пользоваться сайтом, вы соглашаетесь на их использование в соответствии с Политикой в отношении обработки cookie ООО «ППГ», в том числе на передачу данных из файлов cookie сторонним статистическим и рекламным службам. Вы можете управлять настройками cookie через параметры вашего браузера