Sergey Kozlov
Sergey Kozlov

Reputation: 452

Postgresql select count with join

I have two tables:

CREATE TABLE stores (
stores_id varchar PRIMARY KEY,
owner_id varchar
);

CREATE TABLE sets (
sets_id varchar PRIMARY KEY,
stores_id varchar not null,
owner_id varchar not null,
item_id varchar not null,
);

How do I make a request that shows the number of items on the sets in stores? With selection by owner.

For example:

select
stores.*,
count(sets.item_id)
from stores
LEFT OUTER JOIN sets on stores.owner_id = sets.owner_id
where
stores.owner_id = 'e185775fc4f5'
GROUP BY stores.owner_id;

Thank you.

Upvotes: 1

Views: 5301

Answers (2)

I think you'd need to join on both the store and the owner, then COUNT(DISTINCT item_id)

select
st.owner_id, 
st.stores_id, 
count(distinct se.item_id)
  from stores st left join
    sets se
       on st.owner_id = se.owner_id
       and st.stores_id = se.stores_id
           group by st.owner_id, st.stores_id;

That will give a table that shows the owner, the store, then the number of items

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269563

Is this what you want?

select st.stores_id, count(se.item_id)
from stores st left join
     sets se
     on st.owner_id = se.owner_id
where st.owner_id = 'e185775fc4f5'
group by st.stores_id;

Upvotes: 1

Related Questions