Home > Blockchain >  SQL How to combine multiple rows with same post_id into one using response values to create columns
SQL How to combine multiple rows with same post_id into one using response values to create columns

Time:06-03

I'm pretty sure my problem has very simple solution and was asked somewhere before, so I believe it's not big deal for you to help me.

First of all I have query:

SELECT * 
FROM wp_postmeta 
WHERE post_id = 340 
AND (
     meta_key = '_regular_price' 
     OR meta_key = 'multiplier' 
     OR meta_key = 'multiplier_filter' 
     OR meta_key = 'price_filter' 
     OR meta_key = 'attribute_size' 
     OR meta_key = 'live_update'
    );

So as you can see I work with wordpress and everything here works but I would like to change interpretation of the response.

Now it looks like:

meta_id post_id meta_key meta_value
8197 200 price 100
9209 200 filter 2
9208 200 update true

But it would be ideal if it starts giving response in this format:

post_id price filter update
200 100 2 true

CodePudding user response:

Use a pivot query:

SELECT post_id,
       MAX(CASE WHEN meta_key = 'price'  THEN meta_value END) AS price,
       MAX(CASE WHEN meta_key = 'filter' THEN meta_value END) AS filter,
       MAX(CASE WHEN meta_key = 'update' THEN meta_value END) AS `update`
FROM yourTable
GROUP BY post_id;
  • Related