Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE statement with condition when one column is NULL

Tags:

sql

mysql

Let's say I have

ID       |   Column 1 | Column 2
  2      |      NULL  |     "a"
  3      |      "b"   |    NULL
  4      |       "c"  |     "c"

What I want to write is this:

 SELECT ID FROM table, AnotherTable 
  WHERE (Table.Column1 = AnotherTable.Column IF Table.Column1 IS NOT NULL 
     OR Table.Column2 = AnotherTable.Column IF Table.Column2 IS NOT NULL)

EDIT: I am also adding the case IF Table.Column1 IS NOT NULL AND Table.Column2 IS NOT NULL THEN CHOOSE Table.Column2 = AnotherTable.Column

like image 258
user461316 Avatar asked Dec 21 '12 16:12

user461316


1 Answers

You can use the COALESCE() function:

SELECT ID
FROM   table JOIN AnotherTable
               ON AnotherTable.Column = COALESCE(table.Column1, table.Column2)
like image 78
eggyal Avatar answered Sep 28 '22 22:09

eggyal