我有两个不相关的表,但我想将它们加入到一个查询中,这可能吗?
这是我使用交叉连接的方式,但它不起作用
table 1
| ID | Amount |
| 1 | 20 |
| 2 | 10 |
| 3 | 21 |
| 4 | 50 |
table 2
| ID | Paid Value |
| 011 | 5 |
| 052 | 2 |
//我试过的查询
SELECT
a.`Amount`,
b.`Paid Value`
FROM
`table 1` a
CROSS JOIN
`table 2` b
这是我使用上述查询获得的回报
| ID | Amount | Paid Value |
| 1 | 20 | 5 |
| 2 | 10 | 2 |
| 3 | 21 | 5 |
| 4 | 50 | 2 |
然而,这是我的预期结果
| ID | Amount | Paid Value |
| 1 | 20 | 5 |
| 2 | 10 | 2 |
| 3 | 21 | 0 |
| 4 | 50 | 0 |
答案 0 :(得分:2)
您希望通过某些隐式行号加入。我假设这是基于id
的排序。您可以使用变量来计算行号,然后将其用于连接:
select t1.id, t1.amount, coalesce(t2.paidvalue, 0)
from (select t1.*, (@rn := @rn + 1) as rn
from table1 t1 cross join
(select @rn := 0) vars
order by id
) t1 left join
(select t2.*, (@rn2 := @rn2 + 1) as rn
from table1 t2 cross join
(select @rn2 := 0) vars
order by id
) t2
on t1.rn = t2.rn;