Counting records in a child table
| От | Mike Orr |
|---|---|
| Тема | Counting records in a child table |
| Дата | |
| Msg-id | AANLkTimUAJ8b5xKMDwzzDwYPSrhTQSx+iWbOdX87P36G@mail.gmail.com обсуждение исходный текст |
| Ответы |
Re: Counting records in a child table
|
| Список | pgsql-general |
I know how to do count(*)/group by on a single table, but how do I get
a count of related records in a child table? Some of the counts will
be zero.
SELECT
parent.id AS id,
parent.name AS name,
parent.create_date AS create_date,
COUNT(child.id) AS count
FROM parent LEFT JOIN child ON parent.id = child.parent_id
GROUP BY parent.id, parent.name, parent.create_date
ORDER by count desc;
Is this correct, and is it the simplest way to do it?
I used a left join to avoid skipping parent records that have no child
records. I grouped by parent.id because those are the result rows I
want. I added the other group by fields because psql refused to run
the query otherwise.
--
Mike Orr <sluggoster@gmail.com>
В списке pgsql-general по дате отправления: