I have 3 tables:
users(id, account_balance)
grocery(user_id, date, amount_paid)
fishmarket(user_id, date, amount_paid)
Both fishmarket
and grocery
tables may have multiple occurrences for the same user_id with different dates and amounts paid or have nothing at all for any given user.
When I try the following query:
SELECT
t1."id" AS "User ID",
t1.account_balance AS "Account Balance",
count(t2.user_id) AS "# of grocery visits",
count(t3.user_id) AS "# of fishmarket visits"
FROM users t1
LEFT OUTER JOIN grocery t2 ON (t2.user_id=t1."id")
LEFT OUTER JOIN fishmarket t3 ON (t3.user_id=t1."id")
GROUP BY t1.account_balance,t1.id
ORDER BY t1.id
It produces an incorrect results: "1", "12", "12"
.
But when I try to LEFT JOIN
to just one table it produces a correct results for either grocery
or fishmarket
visits, which are "1", "3", "4"
.
What am I doing wrong here?
I am using PostgreSQL 9.1.