Home >Database >Mysql Tutorial >How Can I Pivot a MySQL Table with Dynamic Column Names from Row Values?

How Can I Pivot a MySQL Table with Dynamic Column Names from Row Values?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-13 20:01:43581browse

How Can I Pivot a MySQL Table with Dynamic Column Names from Row Values?

MySQL dynamic row values ​​as column names

MySQL lacks native pivot functionality for legacy table data that has dynamic row values ​​as column names and is displayed in pivot table format. However, prepared statements using GROUP_CONCAT() can help achieve the desired results.

Sample table:

<code class="language-sql">id    name       value
------------------------------
0     timezone   Europe/London
0     language   en
0     country    45
0     something  x
1     timezone   Europe/Paris
1     language   fr
1     country    46</code>

Target output:

<code>id    timezone       language    country  something
---------------------------------------------------
0     Europe/London  en          45       x
1     Europe/Paris   fr          46</code>

Construct the prepared statement as follows:

<code class="language-sql">SELECT CONCAT(
  'SELECT `table`.id', GROUP_CONCAT('
     ,    `t_', REPLACE(name, '`', '``'), '`.value
         AS `', REPLACE(name, '`', '``'), '`'
     SEPARATOR ''),
 ' FROM `table` ', GROUP_CONCAT('
     LEFT JOIN `table`   AS `t_', REPLACE(name, '`', '``'), '`
            ON `table`.id = `t_', REPLACE(name, '`', '``'), '`.id
           AND `t_', REPLACE(name, '`', '``'), '`.name = ', QUOTE(name)
     SEPARATOR ''),
 ' GROUP BY `table`.id'
) INTO @qry FROM (SELECT DISTINCT name FROM `table`) t;

PREPARE stmt FROM @qry;
EXECUTE stmt;</code>

This query dynamically generates a SELECT statement that uses LEFT JOIN to combine rows with the same id value, extracting the corresponding value for a unique name value. Then press id to group the results to generate the desired pivot table format.

Although MySQL lacks native pivot capabilities, this method provides a way to retrieve data from legacy tables with dynamic column names in a structured manner.

The above is the detailed content of How Can I Pivot a MySQL Table with Dynamic Column Names from Row Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn