我需要合并两个表:
一个例子:
table1
date | colA | colB | colC
2011-02-02 | 1.09 | 1.03 | 1.04
table2
date | col1 | col2 | col3 | col4
2011-02-03 | 1.03 | 1.02 | 1.07 | 1.03
查询结果应如下所示:
tableResult
date | colA | colB | colC | col1 | col2 | col3 | col4
2011-02-02 | 1.09 | 1.03 | 1.04 | null | null | null | null
2011-02-03 | null | null | null | 1.03 | 1.02 | 1.07 | 1.03
这不起作用:
INNER JOIN
因为它只返回table1
和table2
之间的交集,OUTER JOIN
仅从左表返回交集+值(如果使用右连接,则返回右表)UNION
因为列数可能不同。任何想法?
了Christoph
答案 0 :(得分:3)
您可以使用仅包含日期列的联合创建临时表,然后使用临时表将左外连接与另外2连接。
示例:
DROP TABLE temptbl IF EXISTS;
CREATE TEMPORARY TABLE temptbl (myDate DATETIME PRIMARY KEY)
AS (SELECT MyDate FROM table1)
UNION (SELECT MyDate FROM table2)
ORDER BY MyDate;
SELECT * FROM temptbl
LEFT OUTER JOIN table1 USING (MyDate)
LEFT OUTER JOIN table2 USING (MyDate);
答案 1 :(得分:0)
select coalesce(t2.data,'')+coalesce(t1.data,'') as data,
t2.col1, t2.col2, t2.col3 ,t2.col4 ,t1.cola ,t1.colb, t1.colc
from table2 as t2
full outer join
table1 t1
on t2.data = 2011-02-03
or t1.data = 2011-02-02