MySQL:不使用JOIN或UNION合并两个不同的表 [英] MySQL: Merge two different tables without JOIN or UNION
本文介绍了MySQL:不使用JOIN或UNION合并两个不同的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要合并两个表:
- 两者都有主键列日期,但是具有不同的值(不同的时间间隔).
- 两者都有不同的(未知)列:我不知道列的名称(两个表中都可能出现相同的列名),我不知道有多少列,但所有列都是相同的类型. /li>
- Both have a primary key-column date, but with different values (different time intervals).
- Both have different (unknown) columns: I don't know the names of the columns (same column-name may occur in both tables), I don't know how many columns, but all of the same type.
一个例子:
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
,因为列数可能不同.
INNER JOIN
because it will only return the intersection betweentable1
andtable2
,OUTER JOIN
returns intersection + values only from left table (or right table if right join is used)UNION
because the count of columns may differ.
有什么想法吗?
Christoph
Christoph
推荐答案
您可以仅使用日期列的并集创建临时表,然后使用该临时表与其他2进行外部联接.
You can create a temp table with the union of just the date column, and then use the temp table to left outer join with the other 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);
这篇关于MySQL:不使用JOIN或UNION合并两个不同的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文