我需要进行以下查询:
我有4个表,第一个是主表,其中'id'在其他3个表中是外来的。我需要获取每个表的日期和描述,它提供id_tabla1。在某些表格中,我记录的记录多于另一张表格。
是否可以将这些表联系起来?
表1主要
表2
表3
表4
我想得到这样的东西:
答案 0 :(得分:1)
这种类型的操作在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;