我有4张桌子:
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
答案 0 :(得分: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
语句。)