我有2个非常简单的表要加入,但是我很想念某个地方,因为我 没有得到想要的输出:
Query:
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
我仍然是一个学习者,如果这里有任何错误,请原谅我。有帮助吗?
这是您不希望做的,只是发布,因为您询问了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
A full outer join between these tables on an impossible condition means you end up with a resultset like:
t1.client_id t2.client_id 9908 NULL NULL 9908
The COALESCE brings the split-ness of it back together:
client_id 9908 9908
如前所述,不这样做-与联合相比,这浪费了数据库的时间和资源。我纯粹是作为一个示例来说明如何 使用JOIN实现结果集的垂直增长,并且还有助于您对db理论和操作的理解:
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
Outer joins preserve the row from the table even if there is no match:
A OUTER JOIN B Results: A1 null null B2
通过使联接成为不可能,完全外部联接将导致结果集在水平和垂直方向上增长:
A OUTER JOIN B ON 1 = 0 Results: A1 null A2 null null B1 null B2
COALESCE返回第一个非null参数,因此,如果我们使用COALESCE(a_column,b_column),它将这两列(其中一个为null)折叠为一列:
acol bcol COALESCE(acol, bcol) result ----|-----|--------------------|-------- A1 null COALESCE(A1, null) -> A1 null B2 COALESCE(null, B1) -> B1