简体   繁体   中英

left join doesn't work - its ignoring the records of the left table

I have 3 tables

Table CUSTOMER

ID NUMBER NAME
--------------------------------------
1  12345  Apple
2  23456  Orange
3  25896  Banana

Table ACCOUNT

 ID    CUST_NUMBR  TYPE    BILLING_FK
 -------------------------------------
 1     12345        B      9876
 2     23456        R      8765
 3     25896        R      7654

Table BILLING

 ID    Start_Date  End_Date 
 -------------------------------------
 1     BLAH       BLAH       
 2     BLAH       BLAH             
 3     BLAH       BLAH       

Relations

  CUSTOMER.NUMBER = ACCOUNT.CUST_NUMBR
  ACCOUNT.BILLING_FK  = BILLING.ID

Sometimes Account won't be found for a Customer, in that case the start date has to be null.

If I try with left join I don't see the customer if it doesn't have a account.

 select name,number,start_date
 from customer left join account on customer.number = account.cust_number,
 billing
 where account.billing_fk = billing.id

How to get the start date as null if there is no account for that customer.

You condition account.billing_fk = billing.id turns your LEFT JOIN into INNER JOIN . It's pretty much eliminating all NULL entries.

select name,number,start_date
from customer 
left join account on customer.number = account.cust_number
left join billing on account.billing_fk = billing.id

It doesn't work because of the following statement in you where clause:

account.billing_fk = billing.id

Try to move it to the left join section

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