2016-01-14 48 views
0

我有一个这样的数据库中的记录:SQL - 如果字段有一个空值,如何创建一个好的查询?

表名:progreen

------------------------ 
id name proid specid 
------------------------ 
1 A01  1  null 
2 A02  19  4 
3 A03  6  2 
------------------------ 

更改为MyQuery:

如果我这样做select * from progreen where proid = 1 and specid = null;结果是null,它应该显示的第一行。

如果我这样做select * from progreen where proid = 19 and specid = 4;它的工作以及

如何创造良好的查询,如果该字段的值为null?

是否使用sql if语句where条款

+0

检查空的操作'是null',不能以' =' –

回答

0

不能使用=操作比较null需要用is null 这里有一些exapmple

mysql> select null= null ; 
+------------+ 
| null= null | 
+------------+ 
|  NULL | 
+------------+ 
1 row in set (0.00 sec) 

mysql> select 1 = null ; 
+----------+ 
| 1 = null | 
+----------+ 
|  NULL | 
+----------+ 
1 row in set (0.00 sec) 

mysql> select 1 is null ; 
+-----------+ 
| 1 is null | 
+-----------+ 
|   0 | 
+-----------+ 
1 row in set (0.00 sec) 

mysql> select null is null ; 
+--------------+ 
| null is null | 
+--------------+ 
|   1 | 
+--------------+ 
1 row in set (0.00 sec) 

所以查询将

select * from progreen where proid = 1 and specid is null; 

http://dev.mysql.com/doc/refman/5.7/en/working-with-null.html

0

尝试使用IS NULL或column_name =''

SELECT * FROM progreen WHERE proid = 1 AND specid = ''; 

OR

SELECT * FROM progreen WHERE proid = 1 AND specid IS NULL; 
1

SELECT * FROM progreen WHERE规范ID IS NULL

0

非常感谢您为大家谁试图回答我的问题。 我试图用这个查询解决我的问题:

select * from progreen 
where proid = 19 --> this value you can insert 1/6 
and IF(specid is null, 1=1, specid = 4) -->this value you can insert null/2 

它的工作非常好。 THX再次

0

添加一些详细信息..

简而言之null是不确定的,但也有其产生一些不同的结果

select 1+null--null 
select 'A'+null--null 

select 1+isnull(null,0) 
select 'A'+isnull(null,'n')--null 


---some info on nulls 

create table #test1 
(
id int, 
name char(5) 
) 


create table #test2 
(
id int 
) 

insert into #test2 
select 2 
union all 
select null 



insert into #test1 
select 1,'a' 
union all 
select null,'b' 
union all 
select 3,null 

--getting data for all non null fields 
select 
* from #test1 where id is not null 

select * from #test1 where id is null 

---all aggregate functions exclude nulls 
select sum(id),max(name) 
from #test1 

---but group by keeps nulls in seperate group 
select 
sum(id),name 
from #test1 
group by name 


---while comparing or joining against other fields --use is null,since we dont know it may be potentiallly null 

select id from #test1 t1 where exists(select 1 from #test2 t2 where t1.id=t2.id)--gives correct results 

select id from #test1 t1 where not exists(select 1 from #test2 t2 where t1.id=t2.id)--gives correct results 


select id from #test1 t1 where id in (select id from #test2)--gives correct results 

select id from #test1 t1 where id not in (select id from #test2)--not gives correct results 
相关问题