Mysql where多条件 可能缺省如何写语句

已知:Mysql 表名 table 字段 a b c d
原来写法 select * from table where a = 1 and b = 2 and c = 3 and d =4;
但是a b c d字段可能给的缺省

前段只给了 a = 1;b =2;c= '' ;d = 4;
我还想这么写 select * from table where a = ? and b = ? and c = ? and d =?;
但是让c=?不判定,怎么办 select * from table where a = ? and b = ? and d =?;

我现在这么做:
String a= request.getParameter("a");
String b= request.getParameter("b");
String b= request.getParameter("c");
String d= request.getParameter("d");
String sql = "select * from table where 1=1 ";

if(!"".equals(a)){
sql += "and a = ?"
}
if(!"".equals(b)){
sql += "and b = ?"
}
if(!"".equals(c)){
sql += "and c = ?"
}
if(!"".equals(d)){
sql += "and d = ?"
}

感觉有点蠢,有好的mysql 语句或者什么办法吗?
我现在用的spring的jdbctemplate
项目没那么大,mybaits感觉用不上

判断每个条件其实不蠢,这样往数据库发送的sql更精简。写在sql里反而是偷懒的做法,比如下面这样

select * from table where a = (case when ? ='' or ? is null then a else ? end ) 

当传空值时,这个sql就会等价为

select * from table where a=a 

相当于没有a条件了,当然前提是你的a列的数据没有null值,如果有null值的话就还要再加点处理,比如

select * from table where (a = (case when ifnull(?,'')='' then a else ? end )  or (ifnull(?,'')='' and a is null))

用mybatis动态标签可以,但是你用原生的jdbctemplate写sql的话,只能代码中去判断拼接了。

不管用什么肯定都是要判断的,不然怎么知道条件要不要生效。就算用mybatis不也得用if或者choose when判断,直接sql的话,也是要用case when判断,像楼上举例一样。

你要是有缺省 你就在provider里面写个判断加到后面 不要用一个句子去完成

img

既然都是原生了,那直接java判断是否为空进行拼接不就完事了

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632