RhymeGuy
RhymeGuy

Reputation: 2112

SQL - How to concatenate this table?

By running this SELECT query:

SELECT wp_posts.ID, wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
INNER JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_status = 'publish' 
AND wp_posts.post_type = 'my_post_type'
AND wp_posts.post_date < NOW()
AND wp_postmeta.meta_key = 'wpcf-lat'
OR wp_postmeta.meta_key = 'wpcf-long'

I get table like this:

id     meta_key     meta_value
------------------------------
1270   wpcf-lat     12.6589
1270   wpcf-long    78.7425
1658   wpcf-lat     22.3654
1658   wpcf-long    65.2985

But I need result table to be like this

id     wpcf-lat     wpcf-long
------------------------------
1270   12.6589      78.7425
1658   22.3654      65.2985

How can I accomplish that?

Upvotes: 1

Views: 59

Answers (3)

legohead
legohead

Reputation: 540

As koushik veldanda said, you can need to pivot the table.

Something like:

SELECT wp_posts.ID, 
CASE WHEN wp_postmeta.meta_key = 'wpcf-lat' THEN wp_postmeta.meta_value END AS wpcf-lat,
CASE WHEN wp_postmeta.meta_key = 'wpcf-long' THEN wp_postmeta.meta_value END AS wpcf-long
FROM wp_posts
INNER JOIN wp_postmeta
    ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_status = 'publish' 
AND wp_posts.post_type = 'my_post_type'
AND wp_posts.post_date < NOW()
AND wp_postmeta.meta_key = 'wpcf-lat'
OR wp_postmeta.meta_key = 'wpcf-long'
GROUP BY wp_posts.ID

I haven't tested this but it should be quite close.

Upvotes: 0

axiac
axiac

Reputation: 72177

A simple while or foreach in your PHP code is the easiest way to put the data in the format you need:

$query = '...';
$resultset = $DB->query($query);

$list = array();
while ($row = $resultset->fetchArray()) {
    // Check if the entry having this ID was created before
    $id = $row['id'];
    if (! isset($list[$id]) {
        // Create a new entry
        $list[$id] = array(
            'id'        => $id,
            'wpcf-lat'  => NULL,
            'wpcf-long' => NULL,
        );
    }

    // Update the corresponding property
    $key = $row['meta_key'];
    $list[$id][$key] = $row['meta_value'];
}

Upvotes: 0

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

For a known set of meta_key you can use the following query

select 
wp.ID, 
max(
   case when pm.meta_key = 'wpcf-lat' then pm.meta_value end
) as `meta_value`,
max(
  case when pm.meta_key = 'wpcf-long' then pm.meta_value end
) as `wpcf-long` 
from wp_posts wp 
join  wp_postmeta pm on pm.post_id = wp.ID 
group by  wp.ID ;

Upvotes: 3

Related Questions