我需要比较两个表(tbl1和tbl2)中的数据,并在新表(tbl_new)中显示它们。
tbl01
------------------------------
price mat_group major
------------------------------
100 a001 a
200 a002 a
450 a003 a
520 b001 b
250 b002 b
170 c001 c
80 c002 c
tbl02
------------------------------
price mat_group major
------------------------------
150 a001 a
180 a002 a
320 a003 a
220 b001 b
350 b002 b
520 c003 c
tbl_new
---------------------------------------------
t1.price t2.price mat_group major
---------------------------------------------
100 150 a001 a
200 180 a002 a
450 320 a003 a
520 220 b001 b
250 350 b002 b
170 c001 c
80 c002 c
520 c003 c
请给我一些MySQL语法?
答案 0 :(得分:0)
使用 LEFT JOIN
的组合。首先使用唯一mat_group
值的子查询连接第一个表,然后将其与第二个表连接。
<强>查询强>
select
`t`.`price_1`,
`t`.`price_2`,
coalesce(`t`.`mat_group_1`, `t`.`mat_group_2`) as `mat_group`,
coalesce(`t`.`major_1`, `t`.`major_2`) as `major`
from(
select
`t1`.`price` as `price_1`,
`t1`.`mat_group` as `mat_group_1`,
`t1`.`major` as `major_1`,
`t2`.`price` as `price_2`,
`t2`.`mat_group` as `mat_group_2`,
`t2`.`major` as `major_2`
from(
select `mat_group` from `tbl01`
union
select `mat_group` from `tbl02`
) as `mg`
left join `tbl01` as `t1`
on `t1`.`mat_group` = `mg`.`mat_group`
left join `tbl02` as `t2`
on `t2`.`mat_group` = `mg`.`mat_group`
) as `t`;
<强> Find a fiddle demo here 强>