当一列为NULL时,带有条件的WHERE语句

时间:2012-12-21 16:38:12

标签: mysql sql

假设我有

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

我想写的是:

 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)

编辑:我也在添加案例IF Table.Column1 IS NOT NULL和Table.Column2 IS NOT NULL,然后选择Table.Column2 = AnotherTable.Column

1 个答案:

答案 0 :(得分:10)

您可以使用COALESCE()功能:

SELECT ID
FROM   table JOIN AnotherTable
               ON AnotherTable.Column = COALESCE(table.Column1, table.Column2)