问题
I am doing an outer join of 2 tables on 2 columns. The join should happen if table1.column1=table2.column1 and table1.column2=table2.column2. Since column2 is allowed to be contain null, the join fails whenever the value is null, since null is not equal to null (only a computer scientist could love that).
The workaround I came up with is:
select table1.column1,table1.colunn1,table2.column1,table2.column2 from
table1
left join table2
on table1.column1=table2.column1
and if(table1.column2 is null,table2.column2 is null, table1.column2=table2.column2)
This works correctly, but there must be a better way?
回答1:
You could use the MySQL null-safe comparison operator <=>:
SELECT t1.column1, t1.column2, t2.column1, t2.column2
FROM table1 t1
LEFT JOIN table2 t2
ON t1.column1 = t2.column1 AND t1.column2 <=> t2.column2
回答2:
I would do LEFT JOIN table2 ON table1.column1 = table2.column1 OR (table1.column1 IS NULL AND table2.column1 IS NULL). I don't know for sure if that would work or not.
(By the way, nulls are not values.)
回答3:
Because NULLs exist in the source data, default the values using COALESCE (or NVL in Oracle) before being used in the LEFT JOIN, to allow the WHERE clause to work as expected. The 'DEFAULT_VALUE' can be whatever you choose, depending on the datatype. This method is effective because it removed confusion and allows the expressions to work properly, without NULLs getting in the way.
Using inline views:
select table1.column1,table1.column1,table2.column1,table2.column2
from
(
select
table1.column1
coalesce(table1.column2,'DEFAULT_VALUE') as column2
from table1
) t1
left join (
select
table2.column1
coalesce(table2.column2,'DEFAULT_VALUE') as column2
from table2
) t2
on t2.column1 = t1.column1
and t2.column2 = t1.column2;
Or using CTEs:
with t1 as
(
select
table1.column1
coalesce(table1.column2,'DEFAULT_VALUE') as column2
from table1
),
t2 as
(
select
table2.column1
coalesce(table2.column2,'DEFAULT_VALUE') as column2
from table2
)
select table1.column1,table1.column1,table2.column1,table2.column2
from t1
left join t2
on t2.column1 = t1.column1
and t2.column2 = t1.column2;
来源:https://stackoverflow.com/questions/11566409/how-to-join-on-when-both-tables-contain-null