代码之家  ›  专栏  ›  技术社区  ›  RhymeGuy

SQL-如何连接此表?

  •  1
  • RhymeGuy  · 技术社区  · 10 年前

    通过运行此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 回复  |  直到 10 年前
        1
  •  3
  •   Abhik Chakraborty    10 年前

    对于已知的 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 ;
    
        2
  •  0
  •   axiac    10 年前

    一个简单的 while foreach 在您的PHP代码中,以您所需的格式放置数据是最简单的方法:

    $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'];
    }
    
        3
  •  0
  •   legohead    10 年前

    正如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
    

    我还没有测试过,但应该很接近。