现在得项目有个需求,就是我接收到一个数组(里面存放的是id),这个数组的长度不确定,因情况不同,从十几到几千都有可能。我现在要做的就是按照数组中id序列,去数据库中查询出相应的结果(id是逐渐),要求查询出的结果就是按数组中id的序列排好的。比如:接收到的数组是 int[] ids = {1,9,3,7,6};我现在需要从数据库中查出的结果结构如下所示:
id   name
 1    张1
 3    张3
 9    张9
 7    张7
 6    张6
这个sql语句该如何构造?

解决方案 »

  1.   

     当然也可以用拼sql的方法!
    StringBuffer sb = new StringBuffer("select * from table1 where ");
      for(int i = 0 ;i<ids.length;i++){
                    if(i!=ids.length){
                      sb.append(" id="+ids[i]+" or");
                     }else{
    sb.append(" id="+ids[i]);
    }

    }
      

  2.   

     忘记了哈 在最后拼好的sql中 sb.append( "order by id");
      

  3.   

    麻烦,最简单的
    String sql="select * from table1 where id in ("+StringUtils.join(ids,",")+") order by id"
    将commons-lang.jar包放入classpath
    该库中有很多有用的工具方法,可以大大大的减少我们的编码量。
    可以在http://commons.apacher.org下载
      

  4.   

    select * from tabe where id in(1,9,3,7,6)
    查询出来的结果就是按照这循序排出来的
      

  5.   

      int[] ids = {1,9,3,7,6};
      String sql="select * from table1 where ids in";
      String s="";
      for(int i=0;i<ids.length;i++)
      {
      s+=ids[i]+",";
      }
      sql=sql+"("+s.substring(0,s.length()-1)+")";
      System.out.println(sql);
      

  6.   

    以上的运行结果select * from table1 where ids in(1,9,3,7,6)
      

  7.   

    这条语句查出来的结果是按升序排列的,我想要的是按照19376的顺序排列。现在简化一点,省去java代码,直接构造sql语句,应该怎么构造才能保证数据库查询出来的结果按照已有的顺序排列?
      

  8.   

    这是一种比较笨的方法,不知是否否和你的要求。1,你可以将要查找的几条信息的id存储在一个ArrayList list1中,
        比如:19376  放在list1中。2,接着你在for循环的查找你要查找19376  id的数据,在讲每一条返回回来的数据存储在一个bean中,然后再将这些分别的bean存储在 另外一个 ArrayList list2 中,
    3,最后你在正对这个list2进行操作。
    注明:这里值考虑实现,没有考虑运行效率等其他情况。