
Dynamic Pivoting in MySQL Using Prepared Statements
MySQL lacks a native PIVOT function, but you can emulate it using aggregate functions and CASE statements. For dynamically pivoting data, prepared statements offer an efficient solution.
Consider a scenario with a table of product parts:
1 2 3 4 5 6 7 8 9 10 11 12 | CREATE TABLE Parts (
part_id INT,
part_type VARCHAR(1),
product_id INT
);
INSERT INTO Parts (part_id, part_type, product_id) VALUES
(1, 'A' , 1),
(2, 'B' , 1),
(3, 'A' , 2),
(4, 'B' , 2),
(5, 'A' , 3),
(6, 'B' , 3);
|
Copy after login
The desired output is a pivoted table summarizing the part IDs for each product:
1 2 3 4 5 | product_id part_A_id part_B_id
---------- ---------- ----------
1 1 2
2 3 4
3 5 6
|
Copy after login
Dynamic Pivoted Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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
Static Pivoted Query (Limited Columns)
For a static query with a fixed number of pivot columns:
1 2 3 4 5 | 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
The above is the detailed content of How to Dynamically Pivot Data in MySQL Using Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!