查询出数据的同时,把数据的条数一并查询出来,这样可以吗?
如果不可以,分两次查询然后一并返回这样会不会有点浪费数据库连接资源?

解决方案 »

  1.   

    我是想把查询数据和查询记录数写在一个SQL语句中,请问改如何写
      

  2.   

    谢谢大家,我还是用个SQL吧,别费劲了,暂时不想用存储过程
      

  3.   

    利用DB的内置函数,比如记录号:identity(int,1,1),当然如果DB不支持类似方法,可以这样(所有DB通用): 
    select *, (select count(*)+1 from mytable as b where b.id>a.id) as recordnum from mytable as a order by a.id; 
    当然这时需要找一个pk栏位,比如id,最好是int类型的,首行记录内包括了数据的条数,如果需要每行记录都包括数据的条数,只需要将重新利用temp表导一次就可以:
    select *, (select count(*)+1 from mytable as b where b.id>a.id) as recordnum from mytable as a order by a.id into temp_mytable; 
    select * , (select max(recordnum ) from temp_mytable) from temp_mytable; 可用的话, 记得给分呀!!!