2014-12-07 39 views
3

從行數據我有4個表:mysql的select查詢得到基於

  • 字段(源字段)
  • source_data
  • source_data_details(source_data的孩子,保存在含有記錄行技術)

enter image description here

source 
id name status 
1  web  active 


field 
id source_id name  config status 
1 1   record_id 101  active 
2 1   firstname 101  active 
3 1   surname 101  active 

source_data 
id source_id status 
1 1   active 
2 1   active 

source_data_details 
id source_data_id source_field_id value 
1  1     1     1avhh2 
2  1     2     john 
3  1     3     mavrick 
4  2     1     87k3jo 
5  2     2     peter 
6  2     3     lyne 

我如何可以查詢它來使結果

source_data.id   record_id firstname surname 
1      1avhh2  john   mavrick 
2      87k3jo  peter  lyne 
+1

這個問題看起來類似︰http://stackoverflow.com/questions/7674786/mysql-pivot-table – 2014-12-07 12:52:11

回答

1

您可以使用多個連接或聚集。以下是使用聚合的示例:

select sdd.source_data_id, 
     max(case when f.name = 'record_id' then sdd.value end) as record_id, 
     max(case when f.name = 'firstname' then sdd.value end) as firstname, 
     max(case when f.name = 'surname' then sdd.value end) as surname 
from source_data_details sdd join 
    field f 
    on sdd.field_id = f.id 
group by sdd.source_data_id; 

請注意,您必須明確地在輸出中插入所需的每一列。如果你想要變量列,那麼你需要使用動態SQL(prepare/execute語句)。

+0

我必須使它動態基於字段table.let我們說,與特定字段並獲取它的source_data_details \ – Ponce 2014-12-08 06:52:03