MySQL - NULL safe NOT equal operator

会有一股神秘感。 提交于 2019-11-28 23:08:04
COALESCE(tab.id, 0) != 1

Can be used here if you like it. I goes through the parameters, and returns the first value that isn't NULL. In this case if it's NULL, it will compare 0 != 1. Although it may use more signs, it's still easier to manage instead of being forced to always have opposite "booleans" as a solution in those cases.

Read documentation for COALESCE()

I found that NOT (NULL <=> 1) works and I think it is also ISO standard compliant, but is cumbersome. A better way to show using column names would be like this: NOT (tbl.col1 <=> 1)

Now MySQL does not have a NULL-safe not equal operator.

Using MySQL the most universal solution is:

!(tab.id <=> 1)

or

NOT tab.id <=> 1

because it will work properly if even in place of 1 you will use NULL.

If you know that the RHS of the comparison IS NOT NULL:

COALESCE(tab.id != 1, 1)

Or

COALESCE(tab.id != 1, TRUE)

will give you the correct result.

Whether this is better more readable than:

(tab.id != 1 OR tab.id IS NULL) 

Is debatable..

I'd also be tempted to filter out the NULL logic first with comparisons, so I don't have to think about them! I'd probably write your first equation as:

(tab.id IS NULL OR tab.id != 1)

Performance will depend on prevalence of NULLs however.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!