2016-03-18 61 views
0

我有兩個查詢都有一個共同的MessageLogID int的結果集。我想要內部連接並獲取更大的tbl1列表,並且只返回與MessageLogID int鍵上的tbl2行相匹配的行。我看到的問題是tbl1.messagelogid無法綁定,因爲它看不到所選的tbl1和tbl2表。如何連接兩個不同大小的SQL結果表的結果

select 
(select messageLogId, localName, action, remoteName, localHost, dateTime, message from Messagelog as mm where (message like '%error>%' or message like '% <nak status ="1">%') 
) as tbl1, 

    (SELECT * FROM 
(
    select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as SQLmessageID from messagelog m 
    where message like '%<NCPDPID>1234567</NCPDPID>%' and dateTime > '3/01/2016' 
) a JOIN 
(
    select 
    substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID, 
    message, 
    messagelogid from messagelog r 
    where 
    dateTime > '3/01/2016' AND 
    message LIKE ('%<RelatesToMessageID>%</RelatesToMessageID>%') 
    and message LIKE ('%<Error>%</Error>%') 
) b ON b.SQLRelatesMessageID = a.SQLmessageID) 
    as tbl2 

    from messagelog where tbl1.messagelogid = tbl2.messagelogid 

回答

2

我想你想以這種形式的東西:

with tbl1 as (select ...), tbl2 as (select ...) 
select tbl1.* 
from 
    tbl1 inner join tbl2 
     on tbl2.MessageLogId = tbl1.MessageLogId 

你也可以做這種方式更接近你似乎在嘗試什麼:

select tbl1.* 
from 
    (select ...) tbl1 
    inner join 
    (select ...) tbl2 
     on tbl2.MessageLogId = tbl1.MessageLogId 
+0

謝謝你許多。 – Jayizzle