2015-06-23 164 views
4

請看下面的表格和結果。檢查我的查詢,並幫助我得到如下結果。SQL加入查詢選擇

Table : incident 
---------------- 
incident_id usr_id item_id 
10059926  191  61006 

Table: act_reg 
-------------- 
act_reg_id act_type_id incident_id usr_id act_type_sc 
454244   1  10059926   191 ASSIGN 
471938  115  10059926   191 TRAVEL TIME 
473379  40  10059926   191 FOLLOW UP 
477652  115  10059926   191 TRAVEL TIME 
477653  107  10059926   191 SITE ARRIVAL 
489091  5000054  10059926   191 ADD_ATTCHMNTS 

Result(Need to get) 
------------------- 
incident_id usr_id item_id Attachment 
10059926  191  61006  Yes 

我的查詢:

SELECT incident.incident_id,incident.usr_id,incident.item_id,Attachemt 
FROM incident RIGHT JOIN act_reg ON incident.incident_id=act_reg.incident_id 
+2

只需使用'INNER JOIN'而不是'RIGHT JOIN'。甚至是'LEFT JOIN'。 –

+0

@GordonLinoff得到同樣的結果 – Salman

+2

@Salman從哪裏得到附件? –

回答

4

如果我理解你的要求,你想從表incident只有行,如果有attchments,這是情況下,如果有至少一個記錄產生額外列表act_reg用相同的incident_id + usr_idact_type_sc=ADD_ATTCHMNTS

我會用CASE WHEN EXISTS

SELECT incident_id, usr_id, item_id, 
     Attachment = CASE WHEN EXISTS 
        (
         SELECT 1 FROM act_reg a 
         WHERE i.incident_id = a.incident_id 
         AND i.usr_id  = a.usr_id 
         AND a.act_type_sc = 'ADD_ATTCHMNTS' 
        ) THEN 'Yes' ELSE 'No' END 
FROM incident i 

Demo

+0

去這個答案,我想它的正確解決方案! –

+0

謝謝Tim Schmelter! – Salman

0

像這樣的東西應該幫助

SELECT incident.incident_id,incident.usr_id,incident.item_id, 
     'Yes' Attachemt 
    FROM incident 
    where exists (select * from act_reg 
        where incident.incident_id = act_reg.incident_id 
        and act_reg.act_type_sc = 'ADD_ATTCHMNTS' 
       ) 
0

不知道是什麼的連接裝置,但如果你希望另一列對您的加入結果你可以使用這個。結果將只包含所需的行

SELECT incident.incident_id,incident.usr_id,incident.item_id, 'yes' 
FROM incident, act_reg WHERE incident.incident_id = act_reg.incident_id;