2016-02-05 47 views
-1

選擇我有以下查詢如何使用邏輯來控制什麼是SQL

select 
    rel.firstobjectuuid, 
    rel.secondobjectuuid 
from 
    Component$ comp 
    inner join Relationship$ rel on comp.objectuuid = rel.firstobjectuuid or comp.objectuuid = rel.secondobjectuuid 
where 
    comp.componentid = '181814' 

有誰知道我怎麼能告訴這個選擇firstobjectuuid時comp.objectuuid = rel.secondobjectuuid。
只有當comp.objectuuid = rel.firstobjectuuid時才選擇rel.secondobjectuuid?

所以基本上,我只希望它返回firstobjectuuid或secondobjectuuid。哪一個是由用於關係$和組件之間的內部連接的相反決定的$

編輯: 我創建了一個小提琴來幫助解釋我可怕的解釋。 http://sqlfiddle.com/#!2/4f655/1

(甲骨文似乎並沒有被工作sqlfiddle,所以我不得不讓MySQL的)

但我希望它有助於解釋什麼,我試圖做的。

+2

也許樣本數據和期望的結果將有助於傳達您想要做的事情。 –

+0

我加了一個小提琴。我試了你的答案,把它沒有返回我想要的。這可能與我想要的相反?我不確定。 – erebel55

回答

0

我得到了這個解碼工作,我從來沒有聽說過,直到現在。

select 
    decode(comp.objectuuid, rel.firstobjectuuid, rel.secondobjectuuid 
         , rel.secondobjectuuid, rel.firstobjectuuid) as final_value 
from 
    Component$ comp 
    inner join Relationship$ rel on comp.objectuuid = rel.firstobjectuuid or comp.objectuuid = rel.secondobjectuuid 
where 
    comp.componentid = '181814' 

編輯:我發現了一個更好的方式,這是數據庫不可知論。

select 
    case comp.objectuuid 
     when rel.firstobjectuuid then rel.secondobjectuuid 
     when rel.secondobjectuuid then rel.firstobjectuuid 
    end 
from 
    Component$ comp 
    inner join Relationship$ rel on comp.objectuuid = rel.firstobjectuuid or comp.objectuuid = rel.secondobjectuuid 
where 
    comp.componentid = '181917' 
1

您可以使用兩次left join來引入不同字段中的匹配項。然後在select中的coalesce()選擇特定的對象ID。

select coalesce(rel1.firstobjectuuid, rel2.secondobjectuuid) 
from Component$ comp left join 
    Relationship$ rel1 
    on comp.objectuuid = rel.firstobjectuuid left join 
    RelationshipType$ reltype1 
    on reltype1.relationshiptypeid = rel1.typeid and 
     reltype1.uuid = 'RelType:Application_Disposition_provides-is_provided_by_Business_Function_UUID' left join 
    Relationship$ rel2 
    on comp.objectuuid = rel.secondobjectuuid left join 
    RelationshipType$ reltype2 
    on reltype2.relationshiptypeid = rel2.typeid and 
     reltype2.uuid = 'RelType:Application_Disposition_provides-is_provided_by_Business_Function_UUID' 
where comp.componentid = '181814' and 
     (reltype1.uuid is not null or reltype2.uuid is not null); 

編輯:

這是一個很難理解的邏輯。或許coalesce()的參數應該是相反的?

select coalesce(rel2.secondobjectuuid, rel1.firstobjectuuid) 

這樣,如果第二個對象匹配,就使用它。否則使用第一個對象。