我有3个表格,其中包含以下架构:
表1列:ID MsgNum Msg 表2列:ID MsgNum SystemId 表3列:ID MsgNum IncidentNum
我希望表1中的所有项目都包含MsgNum,其范围从表2和表3中选择。
从表2中,使用以下SQL获取MsgNum的可能值:
SELECT Table2.MsgNum from Table2 WHERE SystemId = 'Sys-0001'
和表3,
SELECT Table3.MsgNum from Table3 WHERE IncidentNumber = 'Incident-0001'
现在,我想使用从前2个SELECT语句中获取的MsgNum值的组合来获取Table1中的相应行,如下所示:
SELECT * from Table1 where MsgNum IN ( SELECT Table2.MsgNum from Table2 WHERE SystemId = 'Sys-0001' OR SELECT Table3.MsgNum from Table3 WHERE IncidentNumber = 'Incident-0001')
但是这个SQL使用Interactive SQL失败了。我做错了什么?
答案 0 :(得分:2)
为什么不使用EXISTS
SELECT * from Table1 t1
where EXISTS ( SELECT t2.MsgNum from Table2 t2
WHERE t2.SystemId = 'Sys-0001' AND t2.MsgNum = t1.MsgNum)
OR EXISTS (SELECT t3.MsgNum from Table3 t3
WHERE t3.IncidentNumber = 'Incident-0001' AND t3.MsgNum = t1.MsgNum)
答案 1 :(得分:0)
使用UNION命令将两个查询放在一起
SELECT * from Table1 where MsgNum IN (
SELECT Table2.MsgNum from Table2 WHERE SystemId = 'Sys-0001'
UNION
SELECT Table3.MsgNum from Table3 WHERE IncidentNumber = 'Incident-0001')
)
答案 2 :(得分:0)
你的意思是UNION?
SELECT *
from Table1
where MsgNum IN
(
SELECT Table2.MsgNum from Table2 WHERE SystemId = 'Sys-0001'
UNION
SELECT Table3.MsgNum from Table3 WHERE IncidentNumber = 'Incident-0001'
)