简体   繁体   中英

Left join to a table where values do not exist (and are not NULLs)

EDIT (SOLVED): A cross join. One of those joins you never use until you need it. Thanks for the help

Left table : TS , single field with values [1,2,...,365].

Right table : PAYMENT with three fields (ID, TS, AMT)

For each ID, I want to see 365 records from a left join of TS on PAYMENT.

The problem is that "no value" is not the same as a NULL.

If PAYMENT.TS does not exist for a certain value (eg PAYMENT.TS=4), then there is no value to join on and the left join does not return a row #4.

I tried using NOT IN / NOT EXISTS as a condition, but this only treats the case where the right table has explicit NULLS and not the case where no value exists.

How can I proceed? Thanks!

(This is a DB2 system)


SELECT * FROM TS LEFT JOIN PAYMENT ON TS = PAYMENT.TS

TS TABLE:

|   TS   |  
----------
    1           
    2       
   ...        
   365       

PAYMENTS TABLE:

|   ID   |   TS   |    PMT  |
-----------------------------
    1        1         70    
    1        2         20
    1        5         10 
    2        3         200

EXPECTED RESULT:

|   ID   |   TS   |    PMT  |
-----------------------------
    1        1         70 
    1        2         20
    1        3         
    1        4         
    1        5         10
   ...      ...
    1       365  

    2        1 
    2        2 
    2        3         200    
   ...      ...
    2       365 

ACTUAL RESULT:

|   ID   |   TS   |    PMT  |
-----------------------------
    1        1         70 
    1        2         20
    1        5         10
    2        3         200    

You have to join them matching the two common columns in each table. Preferably by the keys(foreign and primary).

Let's say TS table has this one column called 'NUMBERS' and its type is int. The table PAYMENT has the column ID, type of int also. Which means they may have common values. Thus, if you want to join two tables and get the common ones where the PAYMENT.ID exists in TS.NUMBERS then you should do:

SELECT * FROM TS LEFT JOIN PAYMENT ON TS.NUMBERS = PAYMENT.ID

I hope I've been clear.

Note: Also do not forget that if a column or more has the same name in both tables, you have to clarify from which table you want that column for instance if also PAYMENT table had the column named as NUMBERS, then:

SELECT PAYMENT.ID, TS.NUMBERS FROM TS LEFT JOIN PAYMENT ON TS.NUMBERS = PAYMENT.ID

You need to generate all the rows you want using a cross join and then use left join :

SELECT i.id, ts.ts. p.amt
FROM (SELECT DISTINCT ID FROM PAYMENT) i CROSS JOIN
     TS LEFT JOIN
     PAYMENT p
     ON ts.TS = p.TS AND p.id = i.id;

This will return 365 rows for each 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