Mysql按条件查询

来源:互联网 发布:手机辅助软件 编辑:程序博客网 时间:2024/05/23 23:09

这是第二篇关于MySql语句的文章,打算写一系列关于Mysql查询的文章,之所以要写出来,是后期在做项目中遇到过一些比较复杂的查询语句,如果用完就放着不管了,时间

久了就忘记了,所以打算把这些语句写成一系列的文章。

和上一篇文章一样,开发环境不变,使用框架也不变。


java代码部分:

@Responsebody


        @RequestMapping("/XXX.do")


        public void XXX(ModelMap model ,HttpServletRequest request,HttpServletResponse response) {


                int beginIndex_Int = -1;


                int pageSize_Int = 0;


                // 在这里取出需要分页的起始索引以及每页的数据量


                String beginIndex = request.getparameter("beginIndex");


                String pageSize = request.getParameter("pageSize");


               // 因为数据库在分页的时候查询索引和数量不支持字符串,所以需要转换成int型


                if(beginIndex != null){


                        beginIndex_Int = Integer.ParseInt(beginIndex);


                }


                if(pageSize != null){


                        pageSize_Int = Integer.parseInt(pageSize);


                }


                Map<String,Object> map = new HashMap<String,Object>();


                // 把页数和数量放到map集合中


                map.put("beginIndex",beginIndex_Int);


                map.put("pageSize","pageSize_Int");


                // 这里放入要用到的查询条件


                map.put("state","1");


                map.put("number",number);


                // 把map作为参数传到Mapper文件中去


                XXX(map);

        }





sql语句的写法:


    <select  id = "XXX(方法名)"  parameterType = "hashmap" resultMap = "BaseResultMap">


             select * from table(table写自己的表名称)


             where 1 = 1


             <if  test="state != null and state != ' '  ">


                      and state = #{state,jdbcType = INTEGER}


             </if>


             <if test="number != null and number !=' ' ">


                      and (sjrdh like concat ('%',#{number,jdbcType=VARCHAR},'%')


                      or hgh = #{number,jdbcType=VARCHAR})


             </if>


             order by XX(根据某个字段排序) desc


            <if test ="beginIndex != null and beginIndex != -1  ">


                     limit #{beginIndex,jdbcType=INTEGER},#{pageSize,jdbcType=INTEGER}


           </if>


    </select>


原创粉丝点击