查找从表里面日期最后的一条记录(急)
从表b里面有多条记录,里面有时间字段t1,和部门字段d1,和主表a用两个关键字段关联k1,k2,如何查出最近的部门,即时间最靠后的部门呢?
select a.k1,a.k2,b.d1 from a
left join b on a.k1=b.k1 and a.k2=b.k2
------解决方案--------------------修改下你写的:
select k1,k2,d1 from(
select a.k1,a.k2,b.d1 from a
left join b on a.k1=b.k1 and a.k2=b.k2 order by b.t1 desc)
where rownum=1
------解决方案--------------------Select a.k1,a.k2,x.d1 from a
left join b as x on a.k1=x.k1 and a.k2=x.k2
Where not exists(Select * from b Where d1=x.d1 and t1> x.t1)
------解决方案--------------------Select a.k1,a.k2,x.d1 from a
Inner join b as x on a.k1=x.k1 and a.k2=x.k2
Where not exists(Select * from b Where d1=x.d1 and t1> x.t1)
------解决方案--------------------select a.k1,a.k2,b.d1,b.t1 from a, b
where a.k1=b.k1(+) and a.k2=b.k2(+) and b.t1=(select max(t1) from b)
b.t1要建索引
------解决方案--------------------select a.*,b.*
from a,b
where d1 =
( select max(d1)
from
(
select a.k1,a.k2,b.d1 from a
left join b on a.k1=b.k1 and a.k2=b.k2
)
)
and a,k1 = b.k1 and a.k2 = b.k2;
------解决方案--------------------select * from (select a.k1,a.k2,b.d1 from a
left join b on a.k1=b.k1 and a.k2=b.k2 order by b.t1 desc) where rownum=1;
------解决方案--------------------1、b.t1建立索引不管用,因为是时间字段。
2、如果这个表是自己设计的,可以把该字段设置为浮点,然后再建立索引,这样所建立的索引是惯用,可以使用排序的方法。
3、既然:表b里面有多条记录,里面有时间字段t1,和部门字段d1,那么为什么还需要主表a呢,我不是很明白。
------解决方案--------------------
------解决方案--------------------kao,shanhqk(山) ( )
"b.t1建立索引不管用,因为是时间字段。 "
建议你再去学学数据库的基础
------解决方案--------------------楼主只是说最靠后,但是不知道有多少条是吧?如果是这样,在表b里面肯定有个时间最大值吧?这样不就能取出最靠后的部门了吗?
select Select a.k1,a.k2,x.d1 from a
left join b as x on a.k1=x.k1 and a.k2=x.k2
where b.t1 = (select max(t1) from b)
这样就行了。
------解决方案--------------------错了,是:
select Select a.k1,a.k2,x.d1 from a
left join b as x on a.k1=x.k1 and a.k2=x.k2
where x.t1 = (select max(t1) from b)