How to join MySQL tables using a nullable column?

Per picture Per · Aug 6, 2013 · Viewed 9.2k times · Source

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!

Answer

GOTO 0 picture GOTO 0 · Aug 6, 2013

Use the NULL-safe equal operator:

SELECT * FROM A JOIN B ON A.C <=> B.C