MySQL Mysql选择两列不具有相同值的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3825237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql Select Rows Where two columns do not have the same value
提问by Caleb
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 和 column_b 是整数类型,可以包含空值。我试过使用 <> IS NOT 等,但没有任何运气。使用 <=> 很容易找到它们是否相同,但是 <> 和 != 不返回任何行。(使用 MySQL 5.0)。
Thoughts?
想法?
回答by Mark Byers
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 安全运算符,您将不得不这样做:
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)