2017-01-02 45 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;