如何使用逻辑来控制SQL中选择的内容

时间:2016-02-05 21:02:03

标签: sql oracle select

我有以下查询

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'

当comp.objectuuid = rel.secondobjectuuid时,有没有人知道如何告诉我选择firstobjectuuid。
仅在comp.objectuuid = rel.firstobjectuuid时选择rel.secondobjectuuid?

所以基本上,我只希望它返回firstobjectuuid或secondobjectuuid。哪一个与用于Relationship $和Component $

之间的内部联接的相反

编辑: 我创造了一个小提琴来帮助解释我可怕的解释。 http://sqlfiddle.com/#!2/4f655/1

(oracle似乎没有为sqlfiddle工作,所以我不得不把它变成mysql)

但我希望这有助于解释我想要做的事情。

2 个答案:

答案 0 :(得分:1)

您可以使用left join两次来引入不同字段的匹​​配项。然后coalesce()中的select选择特定的对象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)

这样,如果第二个对象匹配,则使用它。否则使用第一个对象。

答案 1 :(得分:0)

我使用了解码,这是我从未听说过的。

decltype(FunctionName)* pointer;

编辑:我找到了一种更好的方法,就是与数据库无关。

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'