SQL 根据连接是否存在,从 table 有条件地查询 select 行
SQL Query to conditionally select a row from a table depending on join existence
我有一个连接 3 table 的查询,我正在尝试根据记录是否存在于第三个 table.
中检索一组条件行
如果第 3 个 table 中有匹配项,那么我只需要第一个 table 中的匹配记录。如果第 3 个 table 没有匹配项,那么我只想要第一个 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'
这会产生以下类型的结果,但以粗体突出显示的是实际需要的行。
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;
第一个查询引入了匹配项。第二个为没有匹配项的每个对象引入一行。
我有一个连接 3 table 的查询,我正在尝试根据记录是否存在于第三个 table.
中检索一组条件行如果第 3 个 table 中有匹配项,那么我只需要第一个 table 中的匹配记录。如果第 3 个 table 没有匹配项,那么我只想要第一个 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'
这会产生以下类型的结果,但以粗体突出显示的是实际需要的行。
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;
第一个查询引入了匹配项。第二个为没有匹配项的每个对象引入一行。