我想合并两个具有相同行的表。 Table1 中的每一行与 table2 中的对应行。
示例:
表1:
| col1 | col2 |
----------
| a | b |
| c | d |
.
.
.
etc
和表2:
| col3 | col4 |
----------
| 2 | 5 |
| 8 | 10 |
.
.
.
etc
结果应该是:
| col1 | col2 | col3 | col4
------------------------------
| a | b | 2 | 5
| c | d | 8 | 10
我该怎么做?
最佳答案
为此您需要一个加入 key 。如果您没有,您可以使用变量创建一个:
select t1.col1, t1.col2, t2.col3, t2.col4
from (select t1.*, (@rn1 := @rn1 + 1) as rn
from table1 t1 cross join
(select @rn1 := 0) vars
) t1 join
(select t1.*, (@rn2 := @rn2 + 1) as rn
from table2 t2 cross join
(select @rn2 := 0) vars
) t2
on t1.rn = t2.rn;
警告:如果没有 order by
子句,SQL 不保证行的排序,因此行可以按任何顺序配对。如果您有所需的排序,请在每个子查询中使用 order by
。
关于mysql - 无需任何键即可连接两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012178/