2017-01-02 67 views
-3

多个表我需要做下面的查询:选择在MySQL

我有4个表,第一个是主要的,在与“ID”是在其他3台国外。我需要获取每个表的id_tabla1的日期和描述。在一些表格中,我有更多的记录。

是否可以将这些表关联起来?

表1主

  1. id_table1
  2. 名称

表2

  1. id_table2
  2. 日期
  3. 描述
  4. fk_table1

表3

  1. id_table3
  2. 日期
  3. 描述
  4. fk_table1

表4

  1. id_table4
  2. 日期
  3. 描述
  4. fk_table1

我想是这样的:

enter image description here

+2

是的......在'fk_table1'列的表中做'JOIN' – Rahul

回答

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;