0

I would just like a join to return 0 rather than dropping rows. Currently, if I try to join the two tables and count the number of items for each subscription, it will work fine:

SELECT S.id, count(I.id) FROM "Subscription" S
LEFT JOIN "Item" I on I.id = S.item_id
WHERE S.status = 1
GROUP BY S.id

returns:

id | count(I.id) 
1       4
2       3
3       2

whereas:

SELECT S.id, count(I.id) FROM "Subscription" S
LEFT JOIN "Item" I on I.id = S.item_id
WHERE S.status = 1
AND I.status IN (1,2,3)
GROUP BY S.id

returns:

id | count(I.id) 
1       3

I realise this is probably how Postgres should work, but Im used to using MySQL.

I've tried aggregate functions to produce the desired effect as well as conditional statements and right, full and outer joins but cannot seem to get it working the way I want.

What if I want to return all of the users with status 1 but show 0 items if they have no items with status 1,2 or 3?

From this documentation it seems like the code Im using should work.

The desired result is:

id | count(I.id) 
1       3
2       0
3       0
1
  • Please try to explain better the expected result that you want Commented Jan 21, 2014 at 15:22

1 Answer 1

2

Try something like:

SELECT S.id, count(I.id) FROM "Subscription" S
LEFT JOIN "Item" I on I.id = S.item_id AND I.status IN (1,2,3)
WHERE S.status = 1
GROUP BY S.id

Your old where clause was filtering the results after the LEFT JOIN turning it into a INNER JOIN.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! You absolute beauty thats been having me round the houses for ages. I wasnt aware you could use "on" and "and" in a join statement. Can you do this in MySQL?
@JackalopeZero Haven't tried it in MySQL but I am 99% sure you can do it in any RDBMS.
@JackalopeZero Of course - a left join predicate is an expression like anything else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.