SQL多个NOT LIKE可能有NULL值

时间:2015-04-09 15:10:23

标签: mysql null sql-like

我正在尝试提取数据,其中多个字段不像'%1%','%2%'和'%3%

但是,这些字段中的一个或多个很容易为NULL,这导致它们在结果中被忽略。我也希望结果具有NULL值。我看到的情况是data1 = 5,data2 = 6,data3为NULL,并且没有返回这些记录。

这是我的问题:

WHERE
region = 'AZ' and
year(date) = '2014' and

data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'

2 个答案:

答案 0 :(得分:0)

在最后添加OR子句

WHERE
region = 'AZ' and
year(date) = '2014' and
(
data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'
OR data1 IS NULL OR data2 IS NULL OR data3 IS NULL
)

答案 1 :(得分:0)

我想出了一个解决方法。我打开了一个测试表,将所有NULL值转换为' 0',然后运行我的查询。它看起来像这样:

Drop table #test
Select
region
, data1
, data2
, data3
into #test

from YourTable

Where
region = 'AZ' and
year(date) = '2014' and
data1 is NULL or 

region = 'AZ' and
year(date) = '2014' and
data2 is NULL or 

region = 'AZ' and
year(date) = '2014' and
data3 is NULL or

--------

UPDATE [#test] SET [data1] = 0 WHERE [data1] IS NULL
UPDATE [#test] SET [data2] = 0 WHERE [data2] IS NULL
UPDATE [#test] SET [data3] = 0 WHERE [data3] IS NULL

--------

Select
region
, data1
, data2
, data3

from #test

Where
data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'