我有表A
============
| id | val |
=====+======
| 1 | abc |
| 1 | def |
| 2 | ghi |
| 2 | jkl |
============
我有表B
============
| id | val2 |
=====+======
| 1 | rty |
| 1 | vbn |
| 2 | uio |
| 2 | zxc |
============
我想像这样显示两个表..
===================
| id | val | val2 |
=====+=====+=======
| 1 | abc | rty |
| 1 | def | vbn |
| 2 | ghi | uio |
| 2 | jkl | zxc |
===================
我的问题是我有裁员..
答案 0 :(得分:1)
是的,您遇到问题,因为您没有合适的join
密钥。您可以使用变量创建一个变量来完成此操作。这样的东西适用于您提供的数据:
select min(id), max(aval), max(bval)
from ((select id, val as aval, NULL as bval, @rna := @rna + 1 as seqnum
from tablea a cross join (select @rna := 0)
) union all
(select id, NULL val, @rnb := @rnb + 1 as seqnum
from tableb b cross join (select @rnb := 0)
)
) ab
group by seqnum;
答案 1 :(得分:0)
您可以使用INNER JOIN
执行此操作。请参阅下面的查询:
SELECT A.id,val,val2 FROM
(SELECT
@row_number:=@row_number+1 AS RowNumber,
id,
val
FROM TableA, (SELECT @row_number:=0) AS t ORDER BY val) AS A
INNER JOIN
(SELECT
@row_number:=@row_number+1 AS RowNumber,
id,
val2
FROM TableB, (SELECT @row_number:=0) AS t ORDER BY val2) AS B
ON A.RowNumber=B.RowNumber
答案 2 :(得分:0)
我喜欢Gordon的方法,因为它不假设每个表中的行数相同,但这里是JOIN
版本:
SELECT a.id,a.val,b.val2
FROM (SELECT @row_number:=@row_number+1 AS row_number
,id,val
FROM Table1 a cross join (select @row_number := 0) b
)a
JOIN (SELECT @row_number2:=@row_number2+1 AS row_number2
,id,val2
FROM Table2 a cross join (select @row_number2 := 0) b
)b
ON a.Row_Number = b.Row_Number2
AND a.id = b.id
这是他的UNION
版本的工作版本:
SELECT Row_Number,ID,MAX(Val) AS Val,MAX(Val2) AS Val2
FROM (SELECT @row_number:=@row_number+1 AS row_number
,id,val,NULL as Val2
FROM Table1 a cross join (select @row_number := 0) b
UNION ALL
SELECT @row_number2:=@row_number2+1 AS row_number
,id,NULL,val2
FROM Table2 a cross join (select @row_number2 := 0) b
)sub
GROUP BY Row_Number,ID
两者的演示:SQL Fiddle