[英]SQL Query to conditionally select a row from a table depending on join existence
I have a query that joins 3 tables and I am trying to retrieve a conditional set of rows depending on whether the record exists in the third table. 我有一个连接3个表的查询,我试图检索一个条件行集,具体取决于该记录是否存在于第三个表中。
If there is a match in the 3rd table then I just want the matching records from the 1st table. 如果第3个表中有匹配,那么我只想要第1个表中的匹配记录。 if there isn't a match from the 3rd table then I just want one record from the first table. 如果第三张表中没有匹配,那么我只想要第一张表中的一条记录。
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'
This produces the following type of result, but the ones highlight with in Bold are the actual rows that are required. 这会产生以下类型的结果,但在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
One solution is union all
: 一个解决方案是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;
The first query brings in the matches. 第一个查询引入匹配。 The second brings in the one row per object that has no match. 第二个引入每个对象的一行没有匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.