我有一个有3列的表:(int) test1
, (int) test2
和(int) test3
。
NULL
。例如:╔═══╦════════════╦═════════════╦═════════════╗
║ ║ test1 ║ test2 ║ test3 ║
╠═══╬════════════╬═════════════╬═════════════╣
║ 1 ║ 123 ║ 456 ║ NULL ║
║ 2 ║ 456 ║ 456 ║ NULL ║
║ 3 ║ NULL ║ NULL ║ NULL ║
╚═══╩════════════╩═════════════╩═════════════╝
我想获得每个条目,其中test1
不是"123",test2
不是"123",test3
不是"123"。我需要每个条目都有一个数字,而不是"123"或NULL
。
SELECT * FROM table WHERE test1 != "123" AND test2 != "123" AND test3 != "123";
问题是,我没有得到任何条目,因为到处都必须有一个数字。在这个例子中,我想获得条目2和条目3,但不是第一个,因为在test1
列中有一个"123"。
我该怎么做呢?
null
不是一个值-它是缺乏值。当在任何需要值的上下文中使用时,它返回"unknown",即使是!=
操作符。为了处理null
s,应该显式地使用is
操作符:
SELECT *
FROM mytable
WHERE (test1 IS NULL OR test1 != 123) AND
(test2 IS NULL OR test2 != 123) AND
(test3 IS NULL OR test3 != 123)
使用ifnull()
将空值转换为包含的数字:
SELECT * FROM table
WHERE ifnull(test1, 0) != "123"
AND ifnull(test2, 0) != "123"
AND ifnull(test3, 0) != "123";
您可以使用isnull(column, 0).我假设列是整数:
create table #x (test1 int null, test2 int null, test3 int null)
go
insert #x select 123, 456, null
insert #x select 456, 456, null
insert #x select null, null, null
SELECT * FROM #x WHERE isnull(test1,0) != 123 AND isnull(test2,0) != 123 AND isnull(test3,0) != 123
test1 test2 test3
----------- ----------- -----------
456 456 NULL
NULL NULL NULL
您需要使用NOT IN函数和NULL函数:
SELECT * FROM table
WHERE (test1 not in ("123","others") or test1 is NULL)
and (test2 not in ("123","others") or test2 is NULL)
等等……
应该可以处理这个:
SELECT * FROM table
WHERE (test1 != "123" OR test1 is null)
AND (test2 != "123" OR test2 is null)
AND (test3 != "123" OR test3 is null);