Adding the results of a column to another column

I need to show the contents of two tables; my query is this:

SELECT ID, 
    post_author, 
    post_content, 
    post_title, 
    post_name, 
    guid, 
    post_type, 
    meta_id, 
    post_id, 
    meta_key, 
    meta_value 
FROM wp_posts, 
    wp_postmeta 
WHERE wp_posts.ID = wp_postmeta.post_id 
    AND post_author IN (2);

The meta_key column stores the TYPE of content I need like website, latitude, longitude, phone, email. Is there a way to make this column explode to another columns? For example:

ID, 
post_author, 
..., 
meta_id, 
post_id, 
meta_key, 
meta_value, 
website(its a meta_key result), 
latitude(another meta_key result), 
longitude(anoter meta_key result)...

Related posts

Leave a Reply

1 comment

  1. It is not clear what are you trying to do, but I think you need to display the meta key and values as columns’ headers with the meta values as the values for each column. In this case you can do something like this:

    SELECT  
      ID, 
      post_author, 
      post_content,   
      post_title, 
      post_name, 
      guid, 
      post_type, 
      meta_id, 
      post_id, 
      MAX(CASE WHEN meta_key = 'website'   THEN meta_value END) AS website,
      MAX(CASE WHEN meta_key = 'latitude'  THEN meta_value END) AS latitude,
      MAX(CASE WHEN meta_key = 'longitude' THEN meta_value END) AS longitude,
      ...
    FROM wp_posts
    INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
    WHERE post_author IN (2)
    GROUP BY Id, post_author, ...
    

    Things to note:

    • Try to avoid the old JOIN syntax that you used in your query; it is a bad habit , and use the ANSI-SQL-92 syntax using the JOIN key word instead like what I did.

    • I used the MAX as a work around to pivot the rows into columns, you will need to list the columns that are not in the aggregate function in the GROUP BY clause.