获取表格中的前100条记录

时间:2014-08-08 16:00:58

标签: oracle rownum

我有一个包含数百万行的庞大数据库,我的查询中包含多个表。我想测试我的查询,以便我知道我的查询是否正常工作。

如果我运行我的查询,它将花费数小时来提供查询的输出,并在阅读了oracle中的Rownum之后我尝试了但是rownum仅在查询执行后执行。

有没有快速的方法来测试我的查询,以便我可以显示前100行。

select 
p.attr_value product,
m.attr_value model,
u.attr_value usage,
l.attr_value location
    from table1 t1 join table2 t2 on t1.e_subid = t2.e_subid
                   join table4 t4 on t4.loc_id = t1.loc_id
                   join table3 p  on t2.e_cid = p.e_cid 
                   join table3 m  on t2.e_cid = m.e_cid 
                   join table3 u  on t2.e_cid = u.e_cid 
  Where
      t4.attr_name = 'SiteName' 
      and p.attr_name  = 'Product'
      and m.attr_name  = 'Model'
      and u.attr_name  = 'Usage'
      order by product,location;

attempt1:获取前100名

的查询结果
select 
p.attr_value product,
m.attr_value model,
u.attr_value usage,
l.attr_value location
    from table1 t1 join table2 t2 on t1.e_subid = t2.e_subid
                   join table4 t4 on t4.loc_id = t1.loc_id
                   join table3 p  on t2.e_cid = p.e_cid 
                   join table3 m  on t2.e_cid = m.e_cid 
                   join table3 u  on t2.e_cid = u.e_cid 
  Where
      ROWNUM <= 100 
      and t4.attr_name = 'SiteName' 
      and p.attr_name  = 'Product'
      and m.attr_name  = 'Model'
      and u.attr_name  = 'Usage'
      order by product,location;

我确实尝试了上述内容,但是我在几分钟的时间内得到了一些结果,但不确定这是否是正确的做法...你觉得怎么样?

1 个答案:

答案 0 :(得分:1)

试试这个以获得100条记录:

  select 
p.attr_value product,
m.attr_value model,
u.attr_value usage,
l.attr_value location
    from table1 t1 join table2 t2 on t1.e_subid = t2.e_subid
                   join table4 t4 on t4.loc_id = t1.loc_id
                   join table3 p  on t2.e_cid = p.e_cid 
                   join table3 m  on t2.e_cid = m.e_cid 
                   join table3 u  on t2.e_cid = u.e_cid 
  Where
      t4.attr_name = 'SiteName' 
      and p.attr_name  = 'Product'
      and m.attr_name  = 'Model'
      and u.attr_name  = 'Usage'
      and ROWNUM <= 100
      order by product,location;

另请注意,Oracle在返回结果后会对结果应用 rownum

但是,您可以尝试使用以下方法检查表中是否存在该值:

select case 
            when exists (select 1
        from table1 t1 join table2 t2 on t1.e_subid = t2.e_subid
                       join table4 t4 on t4.loc_id = t1.loc_id
                       join table3 p  on t2.e_cid = p.e_cid 
                       join table3 m  on t2.e_cid = m.e_cid 
                       join table3 u  on t2.e_cid = u.e_cid 
      Where
          t4.attr_name = 'SiteName' 
          and p.attr_name  = 'Product'
          and m.attr_name  = 'Model'
          and u.attr_name  = 'Usage'
          order by product,location;
) 
    then 'Y' 
            else 'N' 
        end as rec_exists
from dual;