我有 3 张桌子:
users(id, account_balance)
grocery(user_id, date, amount_paid)
fishmarket(user_id, date, amount_paid)
fishmarket
和表都grocery
可能多次出现相同的 user_id 具有不同的日期和支付的金额,或者对于任何给定的用户根本没有任何内容。当我尝试以下查询时:
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
它会产生不正确的结果:"1", "12", "12"
.
但是,当我尝试只使用一个表时,它会为任一或访问LEFT JOIN
产生正确的结果,即.grocery
fishmarket
"1", "3", "4"
我在这里做错了什么?
我正在使用 PostgreSQL 9.1。