I have three MYSQL tables, simplified, with following columns:
ModuleEntries (MDE_ID)
ModuleFields (MDF_ID, MDF_Label)
ModuleEntryFieldValues (MFV_ID, MFV_MDE_ID, MFV_MDF_ID, MFV_Value)
As you can see from the simplified column list, ModuleEntryFieldValues
is the table which states that "for an entry, this field has this value".
Now, I would like to retrieve this information in one "flat" recordset. I have managed to get things working, but not entirely to what i want.
With the help of a different SO article, I managed to get the dynamic, variable amount of columns to work, by using a cursor.
declare finish int default 0;
declare fldid int;
declare str varchar(10000) default 'SELECT *,';
declare curs cursor for select MDF_ID from ModuleFields group by MDF_ID;
declare continue handler for not found set finish = 1;
open curs;
my_loop:loop
fetch curs into fldid;
if finish = 1 then
leave my_loop;
end if;
set str = concat(str, 'max(case when MFV_MDF_ID = ',fldid,' then MFV_Value else null end) as field_',fldid,',');
end loop;
close curs;
set str = substr(str,1,char_length(str)-1);
set @str = concat(str, ' from ModuleEntries LEFT join ModuleEntryFieldValues ON MDE_ID = MDF_MDE_ID GROUP BY MDE_ID');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;
What this code doesn't do, is allow me to put the column values of MDF_Label
as the actual column headers of the rows. Now, the above code gives me "field_1, field_2, ..."
Is it possible to join these three tables, and have the
MDF_Label
as column header for the rows that are now columns in the joined table ?I want this...
ModuleEntries | ModuleFields | ModuleEntryFieldValues
------------- | ------------------ | -----------------------------------
MDE_ID | MDF_ID - MDF_Label | MFV_MDE_ID - MFV_MDF_ID - MFV_Value
1 | 1 - Height | 1 - 1 - 120cms
| 2 - Width | 1 - 2 - 30cms
| 3 - Weight |
into this
Recordset
---------
MDE_ID - Height - Width - Weight
1 - 120cms - 30cms - null
I hope my question was clear enough. If not please comment and I will give more information where needed, if I can.