Dynamic Column MySQL PivotTable Query
P粉262113569
2023-08-27 17:24:10
<p>I use the following table to store product data: </p>
<pre class="brush:php;toolbar:false;">mysql> SELECT * FROM product;
--------------- --------------- --------
| id | name | description | stock |
--------------- --------------- --------
| 1 | product1 | first product | 5 |
| 2 | product2 | second product| 5 |
--------------- --------------- --------
mysql> SELECT * FROM product_additional;
--------------- ----------
| id | fieldname | fieldvalue |
--------------- ----------
| 1 | size | S |
| 1 | height | 103 |
| 2 | size | L |
| 2 | height | 13 |
| 2 | color | black |
------------------ ------------ </pre>
<p>Use the following query to select records from two tables</p>
<pre class="brush:php;toolbar:false;">mysql> SELECT
p.id
,p.name
, p.description
,MAX(IF(pa.fieldname = 'size', pa.fieldvalue, NULL)) as `size`
,MAX(IF(pa.fieldname = 'height', pa.fieldvalue, NULL)) as `height`
,MAX(IF(pa.fieldname = 'color', pa.fieldvalue, NULL)) as `color`
FROM product p
LEFT JOIN product_additional AS pa ON p.id = pa.id
GROUP BY p.id
--------------- --------------- -------- ---------- --- -----
| id | name | description | size | height | color |
--------------- --------------- -------- ---------- --- -----
| 1 | product1 | first product | S | 103 | null |
| 2 | product2 | second product| L | 13 | black |
--------------- --------------- -------- ---------- --- ----- </pre>
<p>Everything is fine :) </p>
<p>Since I'm populating the "additional" table dynamically, it would be great if the query was also dynamic. This way I don't have to change the query every time I enter a new field name and field value. </p>
My approach is slightly different from the accepted answer. This way you avoid using GROUP_CONCAT, which has a default limit of 1024 characters, which won't work if you have a lot of fields unless you change the limit.
Click here to view the demo
The only way to do this dynamically in MySQL is to use prepared statements. Here is a good article about them:
Dynamic PivotTable (convert rows to columns)
Your code will look like this:
SeeDemo
Note: The length of the GROUP_CONCAT function is limited to 1024 characters. View parameter group_concat_max_len