SQL - 如何连接这个 table?

SQL - How to concatenate this table?

通过运行这个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'

我得到 table 这样的:

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

但我需要这样的结果table

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

我怎样才能做到这一点?

对于一组已知的 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 ;

在您的 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'];
}

正如 koushik veldanda 所说,您可能需要旋转 table。

类似于:

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

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