我有一个连接3个表的查询,并且我试图根据记录是否存在于第三个表中来检索条件行集。
如果第三张表中有匹配项,那么我只想要第一张表中的匹配记录。如果第3个表中没有匹配项,那么我只希望第一个表中有一条记录。
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'
这会产生以下类型的结果,但以粗体突出显示的是实际需要的行。
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
答案 0 :(得分:1)
一种解决方案是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;
第一个查询带来匹配项。第二个则为每个不匹配的对象引入一行。