查询"不等于"不起作用

Lin*_*nas 29 mysql sql

我有这样一个非常简单的查询:

SELECT * FROM `all_conversations` WHERE `deleted_1` != '1';
Run Code Online (Sandbox Code Playgroud)

我的deleted_1默认是null或一些用户ID,但由于某种原因这个查询总是返回我0行,我也试过<>但仍然没有运气什么可能是错的?

EDTI因此在运行更多查询后我发现我的问题是deleted_1字段的默认值,NULL所以我修改了我的查询,现在它工作正常:

SELECT *
FROM `all_conversations`
WHERE `deleted_1` != 'NULL'
AND `deleted_1` != 23
Run Code Online (Sandbox Code Playgroud)

Tim*_*lla 72

SELECT * FROM all_conversations WHERE deleted_1 <> 1 OR deleted_1 IS NULL
Run Code Online (Sandbox Code Playgroud)

NULL值需要特殊处理:http://dev.mysql.com/doc/refman/5.1/en/working-with-null.html

我建议使用diamond operator(<>),!=因为第一个是有效的SQL,第二个是MySQL的添加.

  • 我建议使用!=因为更可读,你使用的是mysql,而不是sql :). (3认同)

小智 6

我建议使用NULL-safe运算符和否定

SELECT * FROM `all_conversations` WHERE NOT(`deleted_1` <=> '1');
Run Code Online (Sandbox Code Playgroud)


gre*_*eut 5

你能试试这个吗:deleted_1 is not null and deleted_1 != '1'

mysql> select 0 is not null and 0 != '1', 1 is not null and 1 != '1', null is not null and null != '1';
+----------------------------+----------------------------+----------------------------------+
| 0 is not null and 0 != '1' | 1 is not null and 1 != '1' | null is not null and null != '1' |
+----------------------------+----------------------------+----------------------------------+
|                          1 |                          0 |                                0 |
+----------------------------+----------------------------+----------------------------------+
Run Code Online (Sandbox Code Playgroud)

或这个deleted_1 is null or deleted_1 != '1'

mysql> select 0 is null or 0 != '1', 1 is null or 1 != '1', null is null or null != '1';
+-----------------------+-----------------------+-----------------------------+
| 0 is null or 0 != '1' | 1 is null or 1 != '1' | null is null or null != '1' |
+-----------------------+-----------------------+-----------------------------+
|                     1 |                     0 |                           1 |
+-----------------------+-----------------------+-----------------------------+
Run Code Online (Sandbox Code Playgroud)

这实际上取决于您想拿回什么。