MYSQL多重条件查询的问题
有5个框,每个框都可以输入条件!希望能够实现的是任意一个条件,任意两个条件,任意三个条件,任意四个条件,五个条件都能查找到结果!
以上需求该如何实现?因为有的后面是追加查询条件and xxx = xxx 有的是 where xxx = xxx
希望大家能提供一点思路
//如果关键字KEYWORD不为空
if(typeId != null && !StringUtils.isEmpty(keyword)){
String tmp = "";
if (typeId<2) {
switch (typeId){
case 0:
tmp = "id";
break;
case 1:
tmp = "userId";
break;
}
whereSql = "from Order a where a. "+tmp+" = ?";
params.add(Long.parseLong(keyword));
}else {
whereSql = "from Order a,Ticket b,Attractions c where a.ticketId=b.id and b.jdId = c.id and c.name like ? ";
params.add("%" + keyword + "%");
}
} else {
whereSql = "from Order";
}
//如果订单状态不为空
if(orderStatus != null && !orderStatus.equals(-1)){
whereSql +=" and orderStatus = ?";
params.add(orderStatus);
}
//如果门票状态不为空
if(ticketStatus !=null && !ticketStatus.equals(-1)){
whereSql +=" and ticketStatus = ?";
params.add(ticketStatus);
}
//如果地区不为空
if(areaId !=null){
whereSql += " ";
params.add(areaId);
}
//如果开始时间不为空
if(startTime != null){
whereSql += " and addTime >= ?" ;
params.add(startTime);
}
//如果结束时间不为空
if(endTime != null){
whereSql += " and addTime <= ?";
params.add(endTime);
}
whereSql += " order by " + sort + " " + order;
[最优解释]
//如果开始时间不为空
if(startTime != null){
whereSql += " and addTime >= ?" ;
params.add(startTime);
}
//如果结束时间不为空
if(endTime != null){
whereSql += " and addTime <= ?";
params.add(endTime);
}
if(endTime != null && startTime != null){
whereSql += " and (addTime >= ? and addTime <= ?)" ;
params.add(startTime);
params.add(endTime);
}
[其他解释]
干啥要有and 和where呢?你直接from Order后面跟个where 1= 1然后所有的条件都可以用and了
[其他解释]
SQL写成这样 select * from tab where 1=1
每当用户添加一个条件就增加 and xxx = xxx
这样就可以了
[其他解释]
嗯 楼上 where 1=1 已经告诉你了
有条件才执行后面的 条件 没条件执行 select * from 表 where 1=1 了
[其他解释]
这要看你时间段是什么格式了,是年月日还是年月日时分秒,传的参数格式要和数据库里面对于的格式一致才行。
[其他解释]
可以先直接测试sql语句,跑通了,再检查日期类型、格式。
[其他解释]
小弟马上去试试 谢谢大侠
[其他解释]
谢谢各位 现在是可以了 不过小弟还有一个疑问 因为此查询中有按照时间段 查询 按照上面的写 不知道为什么不行 无法查询出结果 每次都是查询出多有的结果 还望各位指点一二
[其他解释]
直接拼加日期范围的查询条件就可以了撒,这个有什么难度吗?
[其他解释]
该回复于2012-11-28 09:03:43被管理员删除