简体   繁体   中英

I am trying to join tables where a user record does not exist in one of the tables

I have a rewards program with a grants and a purchases table. I am attempting to create a report that displays a users balance. If the user has not made a purchase, however, the balance report does not contain their record. The report only contains users who have earned grants AND made at least one purchase.

The third table being used is our user records table to pull in the user record.

Is there a way to treat no record in the purchases table as a '0' balance?

Could you not have an entry for every user with a 0 balance? That is the reason this wont work. You are asking the database to join/display something that does not exist.

Without the join, you can display no records as 0 but you won't be able to create a join to nothing so I suggest you add an entry for each user (when the users account is created) in the purchases tablet with a 0 balance.

Hope this helps

Something like this should work:

CASE WHEN (SELECT COUNT(*) FROM purchases WHERE purchase_user_id = user_id) > 0
     THEN balance_value
     ELSE 0
 END as balance

EDIT: Going by the query that you added, I think you can just COALESCE the amount to 0 before doing the SUM() . This should prevent returning a NULL value if there are no records in the purchases table.

SELECT ce.platform_id,
       SUM(COALESCE(p.amount, 0))
FROM current_eligibility ce
LEFT JOIN purchases p ON p.platformId = ce.platform_id
WHERE p.currency = 'X123' AND
      ce.platform_id = 'X2334'
GROUP BY ce.platform_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM