mysql - 如何在 MySQL 中连接两个不相关的表?
问题描述
我有两个不相关的表,我需要按照下面的预期输出加入一行。我尝试了以下查询,但不起作用。如何加入这些表?
表格1
| col1 | amount|
| a | 200 |
| b | 100 |
| c | 300 |
| d | 500 |
表 2
| col2 | amount|
| e | 900 |
| f | 800 |
预期输出:
| col1 | Amount | col2 | Amount
| a | 200 | e | 900 |
| b | 100 | f | 800 |
| c | 300 |
| d | 500 |
我试过这个查询
set @a =0; set @b=0;
SELECT
(@a:=@a + 1) AS table1_serial_no,
(@b:=@b + 1) AS table2_serial_no,
table1.col1,
table1.Amount,
table2.col2,
table2.Amount
FROM
table1 left outer
JOIN
table2 ON table1_serial_no = table2_serial_no;
解决方案
select * from
(
select @rn:=@rn + 1 rn from t cross join (select @rn:=0) r
union
select @rn:=@rn + 1 from t1
) allrows
left join
(select col1,amount, @rn1:=@rn1 + 1 rn from t cross join (select @rn1:=0) r) t on t.rn = allrows.rn
left join
(select col2,amount, @rn2:=@rn2 + 1 rn from t1 cross join (select @rn2:=0) r) t1 on t1.rn = allrows.rn
where col1 is not null or col2 is not null;
其中所有行子查询计算出来,将行号分配给最大可能的行数,然后用于连接到分配给 table1 和 table2 的行号。注意没有什么可以订购的,所以没有订购结果..
推荐阅读
- python - How to make every 'beginner' shown at random during the run of the program
- python - 可选的默认参数?
- php - 如何在 Marklogic 的光学 API 查询中使用用户在 Web 应用程序中设置的参数值?
- python - Numpy:尝试在数组切片的切片上设置值
- sql - 与属于父号码的某些号码分组
- node.js - 我的反应项目中哪个是 NodeJS 部分?
- linkedin - 如何将带有“-i --upload-file”的 curl 调用转换为 PHP?
- reactjs - webpack --watch 不想在我的 index.js 中处理反应组件
- java - 多对多关系条目未显示在 Spring REST 中
- c# - 如何在 ASP.NET MVC 5 应用程序中使用 Roslyn?