Mysql选择行两列不具有相同值

时间:2023-02-02 04:24:18

I'm trying to run a query where two columns are not the same, but it's not returning any results:

我正在尝试运行一个查询,其中两列不相同,但它没有返回任何结果:

SELECT * FROM `my_table` WHERE `column_a` != `column_b`;

column_a AND column_b are of integer type and can contain nulls. I've tried using <> IS NOT, etc without any luck. It's easy to find if they're the same using <=>, but <> and != doesn't return any rows. (using Mysql 5.0).

column_a AND column_b是整数类型,可以包含空值。我尝试过使用<> IS NOT等没有运气。使用<=>很容易找到它们是否相同,但<>和!=不会返回任何行。 (使用Mysql 5.0)。

Thoughts?

1 个解决方案

#1


23  

The problem is that a != b is NULL when either a or b is NULL.

问题是当a或b为NULL时,a!= b为NULL。

<=> is the NULL-safe equals operator. To get a NULL-safe not equal to you can simply invert the result:

<=>是NULL安全的等于运算符。要获得不等于NULL的安全性,可以简单地反转结果:

SELECT *
FROM my_table
WHERE NOT column_a <=> column_b

Without using the null safe operator you would have to do this:

如果不使用null safe运算符,则必须执行以下操作:

SELECT *
FROM my_table
WHERE column_a != column_b
OR (column_a IS NULL AND column_b IS NOT NULL)
OR (column_b IS NULL AND column_a IS NOT NULL)

#1


23  

The problem is that a != b is NULL when either a or b is NULL.

问题是当a或b为NULL时,a!= b为NULL。

<=> is the NULL-safe equals operator. To get a NULL-safe not equal to you can simply invert the result:

<=>是NULL安全的等于运算符。要获得不等于NULL的安全性,可以简单地反转结果:

SELECT *
FROM my_table
WHERE NOT column_a <=> column_b

Without using the null safe operator you would have to do this:

如果不使用null safe运算符,则必须执行以下操作:

SELECT *
FROM my_table
WHERE column_a != column_b
OR (column_a IS NULL AND column_b IS NOT NULL)
OR (column_b IS NULL AND column_a IS NOT NULL)