简体   繁体   中英

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM