这种类型的操作是一个有点痛在MySQL中。事实上,结果并不是特别的“关系”,因为每一列都是一个单独的列表。您不能执行join
,因为没有join
密钥。
您可以使用变量在MySQL中生成一个然后使用聚合。这里有两个表的例子:
select id_table1,
max(t2_date) as t2_date,
max(t2_desc) as t2_desc,
max(t3_date) as t3_date,
max(t3_desc) as t3_desc
from ((select id_table1, NULL as t2_date, NULL as t2_desc, NULL as t3_date, NULL as t3_desc, 1 as rn
from table1 t1
) t1 union all
(select fk_table1, date as t2_date, description as t2_desc, NULL as t3_date, NULL as t3_desc,
(@rn1 := if(@fk1 = fk_table1, @rn1 + 1,
if(@fk1 := fk_table1, 1, 1)
)
) as rn
from table1 t1 cross join
(select @rn1 := 0, @fk1 := 0) params
order by fk_table1, date
) t1 union all
(select fk_table1, NULL, NULL, date as t3_date, description as t3_desc
(@rn2 := if(@fk2 = fk_table1, @rn2 + 1,
if(@fk2 := fk_table1, 1, 1)
)
) as rn
from table1 t1 cross join
(select @rn2 := 0, @fk2 := 0) params
order by fk_table1, date
)
) t
group by id_table1, rn;
是的......在'fk_table1'列的表中做'JOIN' – Rahul