如何从postgresql中的UNION第一个表中获取列?

时间:2017-03-01 09:20:34

标签: sql postgresql

我需要获取所有已创建的文件" a@a.com"或shared_to" a@a.com"。以下是实现结果所需的2个表格。

filter_analysis_store

fa_identifier,created_by,case_no
FA000179,a@a.com,01998455
FA000183,a@a.com,01998455
FA000184,a@a.com,02039960
FA000185,a@a.com,02039960
FA000187,a@a.com,02039596
FA000189,a@a.com,02039960
FA000190,a@a.com,02029418
FA000191,a@a.com,02029418
FA000192,a@a.com,02039596
FA000193,a@a.com,02039596
FA000194,a@a.com,02039596
FA000195,a@a.com,01912596
FA000199,a@a.com,02039596

share_analysis_store

fa_identifier,shared_by,shared_to
FA000173,p@p.com,a@a.com
FA000196,p@p.com,a@a.com
FA000180,r@r.com,a@a.com
FA000198,r@r.com,a@a.com

我使用" UNION"提出一个查询,给我结果,但我不得不为第二个查询提供空字符串。如何获取缺少的case_no?

select fas.fa_identifier, fas.case_no as case_no from filter_analysis_store fas  
where created_by like 'a@a.com' UNION 
select sas.fa_identifier, '' from share_analysis_store sas
where shared_to like 'a@a.com';

以上查询的输出

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    

2 个答案:

答案 0 :(得分:0)

试试这个

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 'a@a.com'
  UNION
  SELECT sas.fa_identifier
  FROM share_analysis_store sas
  WHERE shared_to LIKE 'a@a.com'
  ) AS lol
ON lol.fa_identifier = fas.fa_identifier;

答案 1 :(得分:0)

您不需要UNION来生成行,这些创建,共享到&#34; a@a.com" < / em>,一个简单的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 = 'a@a.com'
or        s.shared_to  = 'a@a.com'

distinct on只需生成一次fa_identifier一次。如果这是filter_analysis_store中的主键(或至少是其中的唯一键),那么select distinct fa_identifier, f.case_no就足够了。