举个例子来说明问题,
oracle中有张TEST表,存放如下数据:     ID  SIGNVALUE
---------- ----------
      1096 6.235E-006
      1583 6.098E-006
     ID 是个NUMBER型,SIGNVALUE 为float。
当我想查询,
SELECT * FROM TEST WHERE ID=1500;时
显然表中是没有该条记录,我希望实现:
当查询记录不存在的时候,返回上一条记录。即返回ID=1096的值。请问各位高手如何编写查询语句才能实现这样的功能。注:ID是插入记录时的系统时间与一个指定时间的差值(以秒为单位)。
    实际表中有上千万条的记录。每个ID的差值都不确定,可能是1,也可能是几千。

解决方案 »

  1.   

    select max(id) from tb where id < 1500 and not exists(select 1 from tb where id = 1500)
      

  2.   

    感谢dawugui的回答,可能我没有解说清楚,返回的是signvalue的值,而不是ID的值。你的语句 当所查询的记录存在时,就不能给出结果了。
    改写一下你给的值就可以的出正确的结果。select * from test where id in (select max(id)  from test where id < =1500)
    但是我不希望使用这样的语句,因为表中的记录上千万。select MAX(ID).可能耗费太多时间。不是很使用。我感觉可以用游标,一次读取临近记录的记录快,如果记录不存在,移动一次游标就可以了,但是我刚学orace半个月,不知道怎么用。等待高手解答,或更好的建议。
      

  3.   

    后边这个
    select 1 from tb where id=1500;有什么用?没有用吧?
      

  4.   

    select * from tb where id in(select max(id) from tb where id<=1500)
    ;
      

  5.   

    SQL> create table A(id int,signvalue float);表已创建。SQL> insert into  A values(1,1.2);已创建 1 行。SQL> insert into A values(3,1.5);已创建 1 行。SQL> insert into A values(4,1.8);已创建 1 行。SQL> insert into A values(6,2.5);已创建 1 行。SQL> insert into A values(7,3.2);已创建 1 行。SQL> commit;提交完成。
    SQL> declare
      2  rowa a%rowtype;
      3  cursor c is select * from A;
      4  v_id int:=0;
      5  begin
      6  open c;
      7  
      8  loop
      9  fetch c into rowa;
     10  if c%found then
     11  
     12  if rowa.id-v_id = 1 then
     13  null;
     14  else
     15  dbms_output.put_line('得到的id值='||v_id);
     16  end if;
     17   v_id:= rowa.id;
     18  
     19  else 
     20  exit;
     21  end if;
     22  end loop;
     23  end;
     24  /
    得到的id值=1
    得到的id值=4PL/SQL 过程已成功完成。
      

  6.   


    --Author: phenix;Time:9:46 2009-2-10
    drop table test;
    create table test(id number,signvalue float);
    insert into test values(1096,6.235);
    insert into test values(1583,6.098);
    declare
    cursor c is select * from test order by id;
    v_pre  c%rowtype;
    v_next c%rowtype;
    begin
    open c;
    loop
    fetch c into v_next;
    exit when(c%notfound);
    if(v_next.id=1600) then
    dbms_output.put_line(v_next.id||v_next.signvalue);
    else
    if(v_next.id>1600)then
    dbms_output.put_line(v_pre.id||v_pre.signvalue);
    end if;
    end if;
    v_pre:=v_next;
    end loop;
    if(v_next<1600)then
    dbms_output.put_line(v_pre.id||v_pre.signvalue);
    end if;
    exception
    when others then
    dbms_output.put_line('不存在记录');
    end;