我有两个非常简单的表加入但我错过了某个地方,我没有得到所需的输出:
表格1:
表#2:
期望的输出:
查询:
create table #temp1
(
client_id int,
identifier int,
pp_id int,
ch_id int,
code varchar(20),
program varchar(20),
startdate date,
enddate date,
ssc varchar(50)
)
insert into #temp1
values (9908,789654123,1567,1566,'OP','xASMT','1/1/2019','1/4/2019','A201901044F010134NNN01D 151 143 093 ')
create table #temp2
(
client_id int,
identifier int,
pp_id int,
ch_id int,
code varchar(20),
program varchar(20),
startdate date,
enddate date,
ssc varchar(20)
)
insert into #temp2
values(9908,789654123,1574,1573,'OP','SU1','1/1/2019','1/4/2019',NULL)
--My query:
select
t1.client_id, t1.identifier,
concat(t1.code, t1.startdate, t1.enddate, t1.ssc),
concat(t2.code, t2.startdate, t2.enddate, t2.ssc)
from
#temp1 t1
left join
#temp2 t2 on t1.client_id = t2.client_id and t1.identifier = t2.identifier
Run Code Online (Sandbox Code Playgroud)
如果这里有任何错误,我仍然是学习者并原谅我.有什么帮助?!
我不相信你需要加入,但你需要结合:
select t1.client_id, t1.identifier, CONCAT(t1.code,t1.startdate,t1.enddate,t1.ssc)
from #temp1 t1
union all
select t2.client_id, t2.identifier, CONCAT(t2.code,t2.startdate,t2.enddate,t2.ssc)
from #temp2 t2
Run Code Online (Sandbox Code Playgroud)
也许你需要一个where部分来限制某些行的结果.
看演示
这是您不会做的事情,只是因为您询问了 JOIN 而发帖。这绝对是错误的方法,但是:
select
COALESCE(t1.client_id, t2.client_id) client_id,
COALESCE(t1.identifier, t2.identifier) identifier,
COALESCE(
CONCAT(t1.code,t1.startdate,t1.enddate,t1.ssc),
concat(t2.code,t2.startdate,t2.enddate,t2.ssc)
)
from
#temp1 t1
full outer join
#temp2 t2
on 0 = 1
Run Code Online (Sandbox Code Playgroud)
在不可能的条件下这些表之间的完整外部联接意味着您最终会得到如下结果集:
t1.client_id t2.client_id
9908 NULL
NULL 9908
Run Code Online (Sandbox Code Playgroud)
COALESCE 将其分裂性重新组合在一起:
client_id
9908
9908
Run Code Online (Sandbox Code Playgroud)
如前所述,不要这样做 - 与 union 相比,这是对数据库时间和资源的巨大浪费;我写它纯粹是作为一个例子,说明如何使用 JOIN 实现结果集的垂直增长,也有助于您理解数据库理论和操作:
A UNION B (number is id)
Results grow vertically:
A1
A2
B1
B2
A JOIN B (number is id)
Results grow horizontally:
A1 B1
A2 B2
Run Code Online (Sandbox Code Playgroud)
即使没有匹配,外连接也会保留表中的行:
A OUTER JOIN B
Results:
A1 null
null B2
Run Code Online (Sandbox Code Playgroud)
通过使连接变得不可能,完整的外部连接将导致结果集水平和垂直增长:
A OUTER JOIN B ON 1 = 0
Results:
A1 null
A2 null
null B1
null B2
Run Code Online (Sandbox Code Playgroud)
COALESCE 返回第一个非空参数,所以如果我们 COALESCE(a_column, b_column) 它将这两列折叠成一列,其中一个为空:
acol bcol COALESCE(acol, bcol) result
----|-----|--------------------|--------
A1 null COALESCE(A1, null) -> A1
null B2 COALESCE(null, B1) -> B1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |