Two SQL LEFT JOINS produce incorrect result

后端 未结 3 1798
青春惊慌失措
青春惊慌失措 2020-11-22 08:56

I have 3 tables:

users(id, account_balance)
grocery(user_id, date, amount_paid)
fishmarket(user_id, date, amount_paid)

Both fishmarke

3条回答
  •  余生分开走
    2020-11-22 09:17

    For your original query, if you take away the group by to look at the pre-grouped result, you'll see why the counts your were receiving were created.

    Perhaps the following query utilizing subqueries would achieve your intended result:

    SELECT
     t1."id" AS "User ID",
     t1.account_balance AS "Account Balance",
     (SELECT count(*) FROM grocery     t2 ON (t2.user_id=t1."id")) AS "# of grocery visits",
     (SELECT count(*) FROM fishmarket  t3 ON (t3.user_id=t1."id")) AS "# of fishmarket visits"
    FROM users t1
    ORDER BY t1.id
    

提交回复
热议问题