SQL - 如何连接这个表?

时间:2015-03-18 12:22:16

标签: mysql sql concatenation

通过运行此SELECT查询:

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'

我得到这样的表:

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

但我需要结果表是这样的

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

我该如何实现?

3 个答案:

答案 0 :(得分:3)

对于一组已知的meta_key,您可以使用以下查询

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 ;

答案 1 :(得分:0)

PHP代码中的简单whileforeach是将数据放入所需格式的最简单方法:

$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'];
}

答案 2 :(得分:0)

正如koushik veldanda所说,你可能需要转动桌子。

类似的东西:

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

我没有测试过这个,但它应该非常接近。