Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count how many gifts of each type were sent

I have a gifts table

id | name | price

and a giftings table to record everything that is sent

id | gift | from | to

with giftings.gift being a FK to gifts.id and from and to being FK to a users table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to count how many of each gift a user has received, so an output would be like this

star: 5
diamond: 20
heart: 0

At the moment, I think its working with this query but It wont show a gift if the count is 0.

select gifts.id, gifts.name, count(giftings.gift) from gifts join giftings on gifts.id = giftings.gift where "to" = 5839 group by gifts.id, gifts.name

I have tried different joins, and I know I could do this with a sub query but im trying to do it in a single query because I know its possible.

Many thanks

>Solution :

You need a LEFT join and the condition for the user in the ON clause:

SELECT g.id, g.name, 
       COUNT(s.gift) 
FROM gifts g LEFT JOIN giftings s  
ON g.id = s.gift AND s."to" = 5839 
GROUP BY g.id, g.name;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading