Note that there are some explanatory texts on larger screens.

plurals
  1. POselecting values dynamic from columns using pivoting mysql
    primarykey
    data
    text
    <p>I have a brands table and posts table.</p> <p>Below is their schema </p> <p><strong>Brands</strong> :</p> <blockquote> <p>brands_id, friendly, short ,followers, created, location, brandID, handle, url, pic, utcOffset, posts, engagements, engagedUser, etc(sufficient for current question)</p> </blockquote> <p><strong>Posts</strong> :</p> <blockquote> <p>post_id, brandID, postID, handle, posted, content, postType, comments, etc (sufficient for current question)</p> </blockquote> <p>where postType= link, status,video,question,poll,etc</p> <p>Now I have hardcoded pivoting with the following query:</p> <pre><code>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 </code></pre> <p>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.</p> <p>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.</p> <p>If you haven't understood question, please inform me.</p> <p>I have read the below posts, but unable to figure out:</p> <p><a href="https://stackoverflow.com/questions/12713824/mysql-or-php-turning-rows-into-columns-dynamically">MySQL or PHP Turning rows into columns dynamically</a></p> <p><a href="https://stackoverflow.com/questions/12598120/mysql-pivot-table-query-with-dynamic-columns">MySQL pivot table query with dynamic columns</a></p> <p>Thanks in advance!!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload