2012-04-10 89 views
1

我有一个查询,我试图从查询特定ID的表中提取一些值。如果该值不存在,我仍然希望查询返回一个只有该ID值的记录。这是迄今为止我尝试过的。Oracle SQL:即使特定值不存在也要返回记录

Select attr.attrval, attr.uidservicepoint, sp.servicepointid 
From bilik.lssrvcptmarketattr attr 
Join bilik.lsmarketattrtype type on attr.uidmarketattrtype = type.uidmarketattrtype AND 
type.attrtype IN ('CAPACITY_REQUIREMENT_KW') and TO_CHAR(attr.starttime , 'mm/dd/yyyy')in ('05/01/2011') 
Right Outer Join bilik.lsservicepoint sp on attr.uidservicepoint = sp.uidservicepoint 
Where sp.servicepointid in ('RGE_R01000051574382') Order By sp.servicepointid ASC 

在这个例子中,我试图寻找RGE_R01000051574382。如果表SP.servicepointid中不存在,我希望它仍然返回'RGE_R01000051574382'在一个记录中的空值,以表示我正在抽取的其他值。通常情况下,当我运行这个时,我将一次抽取大约1000个特定值。

如果有任何人有任何洞见,他们可以给予,这将不胜感激。非常感谢!

回答

1

如果我理解正确,您只需要将WHERE子句移入JOIN子句。

select attr.attrval, 
    attr.uidservicepoint, 
    sp.servicepointid 
from bilik.lssrvcptmarketattr attr 
join bilik.lsmarketattrtype type on attr.uidmarketattrtype = type.uidmarketattrtype 
    and type.attrtype in ('CAPACITY_REQUIREMENT_KW') 
    and TO_CHAR(attr.starttime, 'mm/dd/yyyy') in ('05/01/2011') 
right outer join bilik.lsservicepoint sp on attr.uidservicepoint = sp.uidservicepoint 
    and sp.servicepointid in ('RGE_R01000051574382') 
order by sp.servicepointid 
+0

我认为可能是这种情况了,所以我尝试过,但一切确实是“sp.servicepointid”返回每个记录 – user1324945 2012-04-10 20:07:23

1

我想你说你想有一个记录返回,与servicepointid列填充,但所有其他的空?

在这种情况下,请使用联合。

select ...your query without order by... 
and  sp.servicepointid = 'RGE_R010000515743282' 
union 
select null, null, 'RGE_R010000515743282' 
from  dual 
where not exists (select 'x' from (...your query without order by...)) 

这里有一个完整的例子:

create table test (id number, val varchar2(10)); 
insert into test (id, val) values (1, 'hi'); 

select id, 
     val 
from  test 
where id = 1 
union 
select 1, 
     null 
from  dual 
where not exists (select 'x' 
        from  test 
        where id = 1) 
+0

我觉得这可能工作,如果我只有1个ServicePointID,我一直在寻找,但它实际上是大约1000我一直在寻找的具体值。所以,我会寻找“RGE_R010000515743282和RGE_R010000515743283和RGE_R010000515743284等... – user1324945 2012-04-10 20:31:59

+0

在这种情况下,我可能会去一个流水线表函数,其中每次没有找到一个ID,你管一个稀疏行...要么或者使用全局临时表来存储你的“搜索ID”和外部联接。 – krissco 2012-04-10 21:12:50

相关问题