查询某个字段不同值各自最新的一条数据记录SQL语句

时间:2022-07-24 18:02:55

查询各个测站点最新的一条记录:

第一种查询语句

     if(!isNull(stcd)){

//某个测站点最新的一条记录

sql.append("select a.* from dt_water_level a where not exists(select 1 from dt_water_level where stcd = a.stcd and tm > a.tm) and a.stcd='"+stcd+"' order by a.tm desc");
     }

  else{

//各个测站点最新的一条记录

 sql.append("select a.* from dt_water_level a where not exists(select 1 from dt_water_level where stcd = a.stcd and tm > a.tm)  order by a.tm desc");
 

  }


第二种查询语句:

if(!isNull(stcd)){

//某个测站点最新的一条记录

sql.append("select * from dt_water_level a where exists(select * from (select stcd,max(tm) as FTime from dt_water_level group by stcd) x where a.stcd='"+stcd+"' and a.tm=x.FTime )");
     }

  else{

//各个测站点最新的一条记录

 sql.append("select * from dt_water_level a where exists(select * from (select stcd,max(tm) as FTime from dt_water_level group by stcd) x where x.stcd=a.stcd and a.tm=x.FTime)");
 

  }

总结:这两种都是可以查出的,但是第一种放在服务器上执行时会很慢甚至卡死,从导致页面失去响应。故而推荐第二种。对于查询某个测站点的最新一条记录时,语句可以如下:select top 1 * from dt_water_level where stcd='"+stcd+"' order by tm desc

所以最佳的语句是

第三种查询语句:

if(!isNull(stcd)){

//某个测站点最新的一条记录

sql.append("select top 1 * from dt_water_level where stcd='"+stcd+"' order by tm desc");
     }

  else{

//各个测站点最新的一条记录

  sql.append("select * from dt_water_level a where exists(select * from (select stcd,max(tm) as FTime from dt_water_level group by stcd) x where x.stcd=a.stcd and a.tm=x.FTime )");
 

  }


第三种是优化后的最佳语句了!另外,inner join内连接比左外连接快多了,特别是数据多的时候

eg.

查询各个测站点最新的一条水位记录

if(!isNull(stcd)){
sql.append("select top 1 a.*,b.stnm from dt_water_level a inner join tb_station b on a.stcd=b.stcd where a.stcd='"+stcd+"' order by tm desc");

}
else{
sql.append("select a.*,b.stnm from dt_water_level a inner join tb_station b on a.stcd=b.stcd where exists(select * from (select stcd,max(tm) as FTime from dt_water_level group by stcd) x where x.stcd=a.stcd and a.tm=x.FTime )");

}