显示来自不同连接的选择

时间:2018-03-20 15:11:55

标签: sql sql-server tsql join union

select 
m.messageid,    
m.message,
m.orig,     
m.recip, 
d.company as orig_company,
d.department as orig_department,
d.office as orig_office,
d.country as orig_country
from department d
join messages m 
on m.originator = d.address

select
m.messageid,    
m.message,
m.orig,     
m.recip, 
d.company as recip_company,
d.department as recip_department,
d.office as recip_office,
d.country as recip_country
from department d
join messages m 
on m.recip = d.address

我想做一个具有以下信息的选择:

  

messageid,message,orig,recip,orig_company,orig_office,   orig_country,orig_office,recip_company,recip_office,recip_country,   recip_office

怎么办?提前谢谢。

2 个答案:

答案 0 :(得分:4)

<div v-if="vuevar || <%= Poison.encode!(@conn.assigns.elixirvar) %>"> 部门表两次。第一次 orig 值,第二次 recip 值:

LEFT JOIN

答案 1 :(得分:2)

您可以使用UNION ALL。重要的是,两个结果必须具有相同数量的列和数据类型。

select 
    m.messageid,    
    m.message,
    m.orig,     
    m.recip, 

    d.company as orig_company,
    d.department as orig_department,
    d.office as orig_office,
    d.country as orig_country,

    CONVERT(VARCHAR(200), NULL) AS recip_company,
    CONVERT(VARCHAR(200), NULL) AS recip_department,
    CONVERT(VARCHAR(200), NULL) AS recip_office,
    CONVERT(VARCHAR(200), NULL) AS recip_country

from department d
    join messages m 
on m.originator = d.address

UNION ALL

select
    m.messageid,    
    m.message,
    m.orig,     
    m.recip,

    NULL as orig_company,
    NULL as orig_department,
    NULL as orig_office,
    NULL as orig_country

    d.company as recip_company,
    d.department as recip_department,
    d.office as recip_office,
    d.country as recip_country
from department d
    join messages m 
on m.recip = d.address

请检查数据类型VARCHAR(200)是否适合您的情况。 UNION的第一个查询结果会影响生成的数据类型,这就是为什么您需要明确说明您的硬编码NULL将具有哪种类型。