sql 模糊查询like 如何处理 NULL
2015-05-22 20:25
369 查看
今天开发程序时遇到一个问题,我负责前台调用另一个同事写的后台查询方法。我只需要将查询值传给查询方法即可。
表中只有三个字段,表结构如下
deptno、deptname、descript三个字段都是查询条件(也就是where条件)
页面只输入了部门编号是2,其他两列没有值,则为空。
查询sql是 select * from dept where deptno like '%2%' and deptname like '%%'and descript like '%%'
因为用户只要找编号是2的记录,其他条件没有输入,而数据库也有这条记录,按理说应该能查询出来,但是因为descript是NULL,使用like '%%'无法查出NULL的记录,所以就没有查询出。
其实正确的处理方式应该是拼接sql
string sql = "select * from dept where 1=1";
if(deptno != "")
{
sql+= "and deptno like '%'"+deptno+"'%' ";
}
else if(deptname != "")
{
sql+= "and deptnamelike '%'"+deptname+"'%' ";
}
else if(descript != "")
{
sql+= "and descriptlike '%'"+descript+"'%' ";
}
另一种解决方法是利用isnull函数,但因为效率问题还是不赞成使用第二种方法
select * from dept where deptno like '%2%' and isnull(deptname,'') like '%%'and isnull(descript,0) like '%%'
表中只有三个字段,表结构如下
deptno | deptname | descript |
1 | aa | 无 |
2 | bb | NULL |
页面只输入了部门编号是2,其他两列没有值,则为空。
查询sql是 select * from dept where deptno like '%2%' and deptname like '%%'and descript like '%%'
因为用户只要找编号是2的记录,其他条件没有输入,而数据库也有这条记录,按理说应该能查询出来,但是因为descript是NULL,使用like '%%'无法查出NULL的记录,所以就没有查询出。
其实正确的处理方式应该是拼接sql
string sql = "select * from dept where 1=1";
if(deptno != "")
{
sql+= "and deptno like '%'"+deptno+"'%' ";
}
else if(deptname != "")
{
sql+= "and deptnamelike '%'"+deptname+"'%' ";
}
else if(descript != "")
{
sql+= "and descriptlike '%'"+descript+"'%' ";
}
另一种解决方法是利用isnull函数,但因为效率问题还是不赞成使用第二种方法
select * from dept where deptno like '%2%' and isnull(deptname,'') like '%%'and isnull(descript,0) like '%%'
相关文章推荐
- sql 模糊查询like 如何处理 NULL
- sql语句中模糊查询Like中通配符的处理
- 如何在SQL模糊查询中忽略对大小写字符的处理
- CI中自定义SQL查询,LIKE模糊查询的处理
- sql concat like 多字段模糊查询 其中有null
- sql语句模糊查询like的用法
- destoon系统中tag如何使用like与%来进行模糊查询
- 模糊查询:Spring Data JPA 如何进行模糊查询(LIKE) ?
- SQL 模糊查询(like)
- 多字段模糊查询sql like %% 优化与区别
- Oracle sql语言模糊查询--like后面的通配符
- ACCESS模糊查询like的解决方法&&SQL查询语句通配符问题
- SQL中LIKE模糊查询与REGEXP用法说明
- oracle sql语言模糊查询--通配符like的使用教程
- Thinkphp中查询复杂sql查询表达式,如何表达MYSQL中的某字段不为空is not null?
- oracle sql语言模糊查询--通配符like的使用教程
- SQL优化--处理上百万条的数据库如何提高处理查询速度
- Web开发——问题:PreparedStatement如何使用like进行模糊查询
- oracle sql语言模糊查询--通配符like的使用教程
- Oracle模糊查询之(3.2从使用函数和sql语法角度来提高模糊查询效率 二)ORACLE中Like与Instr模糊查询性能大比拼