Home > Database > Mysql Tutorial > How to Perform Dynamic Pivoting in MySQL Using Prepared Statements?

How to Perform Dynamic Pivoting in MySQL Using Prepared Statements?

Mary-Kate Olsen
Release: 2025-01-06 07:31:41
Original
317 people have browsed it

How to Perform Dynamic Pivoting in MySQL Using Prepared Statements?

Dynamic Pivot in MySQL

In MySQL, tables often contain data in a normalized format, requiring complex queries to retrieve data in a more user-friendly format. One such transformation is pivoting, where columns are converted into rows.

Consider a table like "Parts," which relates product parts (part_id) to product types (part_type) and product IDs (product_id). We want to pivot this table to create a new table that shows each product's part IDs for different part types.

MySQL lacks a dedicated PIVOT function, so we need to use alternative techniques. One solution involves using aggregate functions and CASE statements. For dynamic pivoting, we can leverage prepared statements.

Dynamic Pivot Query

The following query uses dynamic SQL to pivot the "Parts" table:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when part_type = ''',
      part_type,
      ''' then part_id end) AS part_',
      part_type, '_id'
    )
  ) INTO @sql
FROM
  parts;
SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                  FROM parts 
                   GROUP BY product_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Copy after login

This query dynamically generates an SQL statement based on the distinct part types present in the table and executes it using prepared statements for improved performance.

Example Result

The resulting table will have the following format:

product_id      part_A_id      part_B_id
----------------------------------------
1               1              2
2               3              4
3               5              6
Copy after login

Static Pivot Query

For a limited number of part types, a static pivot query can be used:

select product_id,
  max(case when part_type ='A' then part_id end) as Part_A_Id,
  max(case when part_type ='B' then part_id end) as Part_B_Id
from parts
group by product_id
Copy after login

This query manually specifies the part types and generates the pivoted table.

The above is the detailed content of How to Perform Dynamic Pivoting in MySQL Using Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template