2017-03-01 40 views
0

我有一個需要獲取所有由created_by「[email protected]」或shared_to「[email protected]」創建的文件。以下是實現結果所需的2個表格。如何從postgresql中的UNION的第一個表中獲取列?

filter_analysis_store

fa_identifier,created_by,case_no 
FA000179,[email protected],01998455 
FA000183,[email protected],01998455 
FA000184,[email protected],02039960 
FA000185,[email protected],02039960 
FA000187,[email protected],02039596 
FA000189,[email protected],02039960 
FA000190,[email protected],02029418 
FA000191,[email protected],02029418 
FA000192,[email protected],02039596 
FA000193,[email protected],02039596 
FA000194,[email protected],02039596 
FA000195,[email protected],01912596 
FA000199,[email protected],02039596 

share_analysis_store

fa_identifier,shared_by,shared_to 
FA000173,[email protected],[email protected] 
FA000196,[email protected],[email protected] 
FA000180,[email protected],[email protected] 
FA000198,[email protected],[email protected] 

我用「聯盟」拿出一個查詢這給我的結果,但我不得不放棄了第二次查詢空字符串。如何獲得各自的case_no缺少的?上面的查詢

FA000184 02039960 
FA000183 01998455 
FA000193 02039596 
FA000199 02039596 
FA000180  
FA000189 02039960 
FA000195 01912596 
FA000185 02039960 
FA000194 02039596 
FA000190 02029418 
FA000191 02029418 
FA000173  
FA000192 02039596 
FA000198  
FA000179 01998455 
FA000187 02039596 
FA000196  
+0

從哪裏可以想象這些缺失值將會出現? –

+0

@TimBiegeleisen:從'filter_analysis_store'第一張表。我只提到了兩個表,可以用來解決這個問題 – Ricky

+0

我相信OP想要結合第一個表和兩個連接? –

回答

1

你並不需要一個UNION產生行,由創建共享「一個@ a.com「,簡單的LEFT JOIN就足夠了(LEFT,因爲fa_identifier可能永遠不會共享)。

select distinct on (fa_identifier) fa_identifier, f.case_no 
from  filter_analysis_store f 
left join share_analysis_store s using (fa_identifier) 
where  f.created_by = '[email protected]' 
or  s.shared_to = '[email protected]' 

distinct on,須出示每fa_identifier只有一次。如果這是filter_analysis_store中的主鍵(或者至少有一個唯一鍵),那麼select distinct fa_identifier, f.case_no就足夠了。

+0

您可以幫助我將此結果與另一個[此處的問題]結合使用(http:// stackoverflow .COM /問題/ 42529403 /如何配搭,一列對結果的查詢,結果到一個表列值和-GET-M)?需要列出每個項目下的所有情況編號 – Ricky

0

select fas.fa_identifier, fas.case_no as case_no from filter_analysis_store fas 
where created_by like '[email protected]' UNION 
select sas.fa_identifier, '' from share_analysis_store sas 
where shared_to like '[email protected]'; 

輸出試試這個

SELECT fas.fa_identifier, 
    fas.case_no 
FROM filter_analysis_store fas 
RIGHT OUTER JOIN 
    (SELECT fas.fa_identifier 
    FROM filter_analysis_store fas 
    WHERE created_by LIKE '[email protected]' 
    UNION 
    SELECT sas.fa_identifier 
    FROM share_analysis_store sas 
    WHERE shared_to LIKE '[email protected]' 
) AS lol 
ON lol.fa_identifier = fas.fa_identifier; 
相關問題