现在有一个表
tbl_d(
Id int
Pdate
)
如果 给1个Id,求出 比该Id 对应 Pdate 小的,离Pdate 最近一条记录。实现如下select max(pdate) into v_pdate from tbl_d where pdate<(select pdate from tbl_d where Id=@id);-- 该记录详细信息
select *
from tbl_d
where pdate =v_pdate ;如果现在有N个 Id,求比各自ID对应Pdate 小的,最近一条记录, 这个怎么实现在一条SQL 语句里面
tbl_d(
Id int
Pdate
)
如果 给1个Id,求出 比该Id 对应 Pdate 小的,离Pdate 最近一条记录。实现如下select max(pdate) into v_pdate from tbl_d where pdate<(select pdate from tbl_d where Id=@id);-- 该记录详细信息
select *
from tbl_d
where pdate =v_pdate ;如果现在有N个 Id,求比各自ID对应Pdate 小的,最近一条记录, 这个怎么实现在一条SQL 语句里面
解决方案 »
- 请问大虾,windows下MYSQL如何用mysqlhotcopy来备份啊
- mysql 创建外键提示ERROR 1064(42000)错误,谢谢
- 同表不同行数据全并
- 并行地从数据库中读取数据
- 关于视图创建mysql5.1 555555555555
- 帮忙设计个文学网站数据库
- 关于EMS PostgreSQL Manager
- 在MYSQL中如何实现查找数据库中相同编号的内容???
- 求一个按时间段查询的方法。
- 求解:mysql表分区后,insert很慢(大数据)
- msyql存储过程查询出某条数据在数据库所有表的表名以及所在表的行数
- MySQL Cluster初步学习资料整理--安装部署新特性性能测试等
create table tbl_d(
Id int primary key,
pdate date
)
insert into tbl_d values(11,'2013-08-08'),(2,'2013-08-07'),(3,'2013-08-06'),(4,'2013-08-05'),(5,'2013-08-04'),(6,'2013-08-03')
如果 当前Id=11 则返回 2013-08-07 对应记录 2,2013-08-07
如果 当前Id=2 则返回 2013-08-06 对应记录 3,2013-08-06
如果 当前Id=5 则返回 2013-08-03 对应记录 6,2013-08-03如果 给出 三个Id 11 3 5
要返回
CurId Id Pdate
11,2,2013-08-07
3, 4,2013-08-05
5 6,2013-08-03
union all
(select 3 as CurId,Id ,Pdate from tbl_d where Pdate<(select Pdate from tbl_d where id=3) order by Pdate desc limit 1)
union all
(select 5 as CurId,Id ,Pdate from tbl_d where Pdate<(select Pdate from tbl_d where id=5) order by Pdate desc limit 1)
from tbl_d c join (
select a.Id, max(b.pdate) as mpdate
from tbl_d a,tbl_d b where b.pdate < a.pdate and a.Id in(3,5,11)
group by a.Id
) d on c.Id=d.Id
join tbl_d e on d.mpdate=e.pdate 刚测试,但是这样写法 当tbl_d 记录多的时候,效率低
join tbl_d e on d.mpdate=e.pdate ,还是可以查出结果,加后面的这一段的作用是什么呢?是可以让查询更快吗?