MySQL/Pivot table for two tables
(Technically, this is 'not an answer', but claim it needs to be said.)

There will be an arbitrary number of columns, correct?  Then (1) the output is impractical, and (2) it would be virtually impossible to generate the output in SQL.

So, (1) rethink the requirement, then (2) consider whether to do it in PHP instead.