I have a brands table and posts table.
Below is their schema
Brands :
brands_id, friendly, short ,followers, created, location, brandID, handle, url, pic, utcOffset, posts, engagements, engagedUser, etc(sufficient for current question)
Posts :
post_id, brandID, postID, handle, posted, content, postType, comments, etc (sufficient for current question)
where postType= link, status,video,question,poll,etc
Now I have hardcoded pivoting with the following query:
select b.friendly,
sum(case when p.postType='link' then 1 else 0 end) as 'link',
sum(case when p.postType='video' then 1 else 0 end) as 'video',
sum(case when p.postType='status' then 1 else 0 end) as 'status',
sum(case when p.postType='photo' then 1 else 0 end) as 'photo',
count(p.postType)
from brands b, posts p
where b.handle
in ('chevroletcanada','dodgecanada')
and p.handle=b.handle
and date(p.posted)
BETWEEN "2013-06-02" and "2013-08-11"
group by b.friendly
But in the above query I have used types of postType statically, i.e for links, status, video, photo. Now if a new postType is added to the posts table, this won't work, as I would have to change the query too. Also if existing values in postType is deleted, then too the query have to be changed again.
My question is how can I achieve this dynamically so that when new postType values for instance tweet is added in posts table then tweet will show up in the result sets as well. And the same for deletion of any postType.
If you haven't understood question, please inform me.
I have read the below posts, but unable to figure out:
MySQL or PHP Turning rows into columns dynamically
MySQL pivot table query with dynamic columns
Thanks in advance!!