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

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

第一种查询语句

     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 )");

}

eg2.

delete    from  [Park_ParkCodes]  where  ParkCodesId  not  in(

select ParkCodesId from [Park_ParkCodes] a
 where exists(
 select * from (select ParkCode,min(AddTime) as FTime from [Park_ParkCodes] group by ParkCode ) x
  where x.ParkCode=a.ParkCode and a.AddTime=x.FTime
  ) 
  )

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值