首页 > 解决方案 > 当条件之一为空时,Mysql xor 运算符无法正常工作

问题描述

我需要为 select 添加一个子句,其中记录等于值或等于 null。

select * 
from table 
where column = 123 or column is null;

结果我得到

|column|
  123
  123
  null
  null

当我尝试使用 xor

select * 
from table 
where column = 123 xor column is null;

我只得到 123 条记录

|column|
  123
  123

或者,如果没有 123,我什么都没有

|栏目|

但我需要,当没有 123 条记录时,只获取空记录。所以基本上我想要的结果是:

|db column|      |column with 123 clause|    |column with 125 clause|
  123                     123                        null
  123                     123                        null
  null
  null
  124

你能帮我解决这个问题吗?

标签: mysqldatabasexor

解决方案


如果没有返回第一行和第二行,您希望返回第三行和第四行,对吗?这不能用一个简单的where子句来表达。尝试

select * from table where column=123
  or column is null and not exists
     (select * from table where column=123)

关于你的xor观察:我认为

column=123 xor column is null

相当于

column=123 and column is not null or
column<>123 and column is null

但是当 时column = null,表达式column<>123为假,因此整体条件也为假。


推荐阅读