Question

I have a list of categories I'm showing on a page.

category1(21)
category2(33)
category3(0)
category4(149)

Each of them shows the amount of items it has. When I click on a category, it shows all the items it has. Pretty straightforward.

I use Postgresql. I wonder, what is the easier and efficient way to retrieve these numbers from db? Well, I know how to select the count of items for one item:

select count(1) from ....

But I have to display all of them for each category at the same time. How do I do that: what data structure should I use? What the query has to look like?

Of course, they should remain in the same order because at a client I have to parse them.

P.S. There are only few categories, like 10-20 and there won't be more for sure.

Was it helpful?

Solution

Hope this may help you.

You should have two tables - 1. category(id, name) 2. items(id, name, catid). I just have taken minimum fields but you may add. catid is the reference of category id in the items table.

Your query should be like -

SELECT c.name as Category, COUNT(i.id) as Items
FROM category as c LEFT OUTER JOIN items  as i ON (c.id= i.catid)
GROUP BY c.id ORDER BY c.name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top