2014-12-07 41 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