Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join MySQL tables using a nullable column?

I'm a little bit out of practice with MySQL, so I hope I can find some advice for my problem here.

Basically I have two tables, call them A and B just for convenience. Both tables have a nullable column C of type varchar. When I join A and B using C, I lose all the rows where C is NULL in either table. I know this is normal in MySQL but what I would like to get is a join that includes combinations of rows where C is NULL in both tables. I found out that the query below seems to work well.

SELECT * FROM A JOIN B ON (A.C IS NULL AND B.C IS NULL) OR (A.C IS NOT NULL AND B.C IS NOT NULL AND A.C = B.C) 

So my question is, is this query the best I can get or is there a way to make this join better? Thanks!

like image 642
Per Avatar asked Aug 06 '13 20:08

Per


People also ask

How do I join a nullable column?

Since it's not possible to join on NULL values in SQL Server like you might expect, we need to be creative to achieve the results we want. One option is to make our AccountType column NOT NULL and set some other default value. Another option is to create a new column that will act as a surrogate key to join on instead.

How do you join a table with NULL values?

Because null values represent unknown or inapplicable values, Transact-SQL has no basis to match one unknown value to another. You can detect the presence of null values in a column from one of the tables being joined only by using an outer join.

Do JOINs work on nulls?

As we have seen from the above examples joining NULL values does not work. Even though you have two NULL values SQL Server does not treat these as the same value. Internally a value of NULL is an unknown value and therefore SQL Server does not equate an unknown value being equal to another unknown value.

How do you inner join with NULL values?

A join that displays only the rows that have a match in both joined tables. Columns containing NULL do not match any values when you are creating an inner join and are therefore excluded from the result set. Null values do not match other null values.


1 Answers

Use the NULL-safe equal operator:

SELECT * FROM A JOIN B ON A.C <=> B.C 
like image 76
GOTO 0 Avatar answered Oct 25 '22 06:10

GOTO 0