繁体   English   中英

SQL Query根据连接存在有条件地从表中选择一行

[英]SQL Query to conditionally select a row from a table depending on join existence

我有一个连接3个表的查询,我试图检索一个条件行集,具体取决于该记录是否存在于第三个表中。

如果第3个表中有匹配,那么我只想要第1个表中的匹配记录。 如果第三张表中没有匹配,那么我只想要第一张表中的一条记录。

select
o.Object_ID,
reqCon.Connector_ID,
req.Object_ID as Requirement_ID

from t_object o

left join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt'
left join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement'

这会产生以下类型的结果,但在Bold中突出显示的结果是所需的实际行。

Object_ID   Connector_ID    Requirement_ID
40936   43259
40936   43260
**40936 43299   38013**
40943   43264
40943   43265
**40943 43298   38014**
**44088 46245**
44088   46246   
**42669 44655**
42669   44656
**42670 44657**
42670   44658

一个解决方案是union all

select o.Object_ID, reqCon.Connector_ID, req.Object_ID as Requirement_ID
from t_object o join
     t_connector reqCon
     on reqCon.End_Object_ID = o.Object_ID and
        reqCon.Stereotype = 'deriveReqt' join
     t_object req
     on reqCon.Start_Object_ID = req.Object_ID and
        req.Stereotype = 'functionalRequirement'
union all
select o.Object_ID, min(reqCon.Connector_ID), null as Requirement_ID
from t_object o left join
     t_connector reqCon
     on reqCon.End_Object_ID = o.Object_ID and
        reqCon.Stereotype = 'deriveReqt' left join
     t_object req
     on reqCon.Start_Object_ID = req.Object_ID and
        req.Stereotype = 'functionalRequirement'
group by o.Object_Id
having sum(req.Object_Id is not null) = 0;

第一个查询引入匹配。 第二个引入每个对象的一行没有匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM