Vous êtes sur la page 1sur 8

Pivot table with dynamic columns in MySQL - Stratos Blog

http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
MYSQL 6
Pivot table with dynamic columns in MySQL
BY STRAPRO SEPTEMBER 19, 2013
DOWNLOAD DEMO
I have already written a post on how to pivot a table in MySQL, when the rows that we want to pivot
into columns are somewhat predefined. If you havent already, now would be a good time to go
ahead and read that article since I will not be explaining everything here.
Pivot a table in MySQL Tutorial

Pivot table with dynamic columns in MySQL - Stratos Blog


http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
Today I am going to show how you can achieve the same result, when the rows that we want to
pivot into columns are not predefined but are dynamic instead. In order to pivot a table with dynamic
columns in MySQL we need to use prepared statements.

What we are trying to achieve is:
1. Get the names of dynamic rows that will become columns with a select statement
2. Concat the field names in proper MySQL syntax
3. Group and distict
4. Inject the result of that statement into another select which will ultimately do the pivot
Here is an example in SQL Fiddle
http://sqlfiddle.com/#!2/0a068/6
Lets take it step by step. First of all lets take a look at this query:
Given the schema and data in the example, if we execute this simple statement, that concats the
value of the column fieldname with some text, we get the following result:
SELECT
CONCAT(
' MAX( I F( pa. f i el dname = ' ' ' ,
f i el dname,
' ' ' , pa. f i el dval ue, NULL) ) AS ' ,
f i el dname
)
FROM pr oduct _addi t i onal ;
Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
MAX(IF(pa.fieldname = size, pa.fieldvalue, NULL)) AS size
MAX(IF(pa.fieldname = height, pa.fieldvalue, NULL)) AS height
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
This is valid MySQL syntax that we will later use to pivot the rows whose fieldname value is size,
height and color. Since we are not using Distinct, we are getting some duplicates but that can be
easily fixed. Also since we are planning on injecting the result of this statement into an other query it
should be returned in one row. In order to make that happen we slightly alter the query to this:
This statement returns one row that we will be able to use later:
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
Now if we were to paste the above result in a simple query that joins the tables product and
product_additional, we would get something like this:
SELECT
GROUP_CONCAT( DI STI NCT
CONCAT(
' MAX( I F( pa. f i el dname = ' ' ' ,
f i el dname,
' ' ' , pa. f i el dval ue, NULL) ) AS ' ,
f i el dname
)
)
FROM pr oduct _addi t i onal ;
SELECT p. i d,
p. name,
p. descr i pt i on,
MAX( I F( pa. f i el dname = ' si ze' , pa. f i el dval ue, NULL) ) AS si ze,
MAX( I F( pa. f i el dname = ' hei ght ' , pa. f i el dval ue, NULL) ) AS hei ght ,
MAX( I F( pa. f i el dname = ' col or ' , pa. f i el dval ue, NULL) ) AS col or
FROM pr oduct p
LEFT J OI N pr oduct _addi t i onal AS pa ON p. i d = pa. i d
GROUP BY p. i d
Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
Which returns a pivoted table.
ID NAME DESCRIPTION SIZE HEIGHT COLOR
1 product1 first product S 103 (null)
2 product2 second product L 13 black
Now the only thing missing is putting it all together. We obviously dont want to paste the code
ourselves in the second query and thats where prepared statements fit in. You see with prepared
statements you can feed the result of one query to an other. So we can have this:
Using this technique, we can pivot a table with dynamic columns in MySQL.
SET @sql = NULL;
SELECT
GROUP_CONCAT( DI STI NCT
CONCAT(
' MAX( I F( pa. f i el dname = ' ' ' ,
f i el dname,
' ' ' , pa. f i el dval ue, NULL) ) AS ' ,
f i el dname
)
) I NTO @sql
FROM pr oduct _addi t i onal ;
SET @sql = CONCAT( ' SELECT p. i d
, p. name
, p. descr i pt i on, ' , @sql , '
FROM pr oduct p
LEFT J OI N pr oduct _addi t i onal AS pa
ON p. i d = pa. i d
GROUP BY p. i d' ) ;
PREPARE st mt FROM @sql ;
EXECUTE st mt ;
DEALLOCATE PREPARE st mt ;
SHARE
Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
Comments 5 Pingbacks 1
Tags: pivot
6 RESPONSES
strapro
I am currently working as a web developer in Greece for an advertising agency but I consider
myself to be an all around technology enthusiast. I like working both front end and back end,
so I guess that makes me a full stack developer. You can find me at Google+, Twitter, Linkedin
and Facebook

Michael Cole March 11, 2014 at 16:29


Hi Great Article
My only question is that say if you wanted to apply filters so in your example were size would equal
small, how would that be done, because you cant just user were size =s
Reply
strapro March 16, 2014 at 15:23
Thanks and sorry for the late reply!
You can use the HAVING clause to apply filters, so it would be something like this
SET @sql =CONCAT(SELECT p.id
, p.name
, p.description, , @sql,
FROM product p
LEFT J OIN product_additional AS pa
ON p.id =pa.id
GROUP BY p.id
HAVING size =S);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Reply

Pelay March 20, 2014 at 16:14


What could be a possible reason for my values returning in BLOB when using MAX().
Reply
Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
strapro March 21, 2014 at 17:04
That would be the result of GROUP_CONCAT.
http://stackoverflow.com/questions/7878695/mysql-group-concat-always-return-blob-i-even-change-all-
the-group-concat-max-len
Reply

Larc April 4, 2014 at 13:30


Hello,
Greetings from Portugal.
You helped me a lot.
Thank you very much, keep up the good work.
Reply
Name * Email *
LEAVE A REPLY
Website
Comment
RECENT POSTS
How to use AJ AX to show progress of a PHP script without polling
4+1 CSS3 animation libraries!
Post Comment
Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
5 effective techniques for encouraging website investment
Vindinium An AI online contest
When to use each CSS Measurement
RECENT COMMENTS
Seluk Okutan on Pivot a table in MySQL Tutorial
strapro on AJ AX Synchronous Call without freezing the UI
strapro on Pivot a table in MySQL Tutorial
Satish kumar on AJ AX Synchronous Call without freezing the UI
grails on Pivot a table in MySQL Tutorial
TWITTER
@strapro
Awesome PHP resources github.com/ziadoz/awesome

@strapro
J avascript library for precise tracking of facial features github.com/auduno/clmtrac

@strapro
How to use AJ AX to show progress of a PHP script without polling stratosprovatopoulos.com/web-developmen


Pivot table with dynamic columns in MySQL - Stratos Blog
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/[03/08/2014 21:38:07]
Stratos Blog 2014. All Rights Reserved.
Powered by WordPress. Theme by Alx.

Vous aimerez peut-être aussi