douwenan9849 2016-10-06 23:00
浏览 36
已采纳

mysql将数据插入另一个

I have following mysql db table structure:

Table_1:

enter image description here

I need to insert the values (post_id and its corresponding geo_lat and geo_lon into another table as below)

Table_2:

enter image description here

This is what I have so far:

$query = "INSERT INTO table_2(post_id,geo_lat,geo_lon)
          SELECT post_id,meta_key IN(geo_lat),meta_key IN(geo_lon) //????
          FROM table_1";
$wpdb->query($query);

Of course it is wrong and I am bit stuck to how to do it (pretty new to php).

Could someone help me with this?

Thanks.

  • 写回答

1条回答 默认 最新

  • douhao2026 2016-10-06 23:42
    关注

    You can use a GROUP BY and MAX together to "rotate" these values:

    INSERT INTO table_2 (Post_id, Geo_lat, Geo_lon)
         SELECT post_id,
                MAX(IF(meta_key='geo_lat',meta_value,NULL)),          
                MAX(IF(meta_key='geo_lon',meta_value,NULL))
           FROM table_1
       GROUP BY post_id
    

    It is kind of self-explanatory, but if you want to understand better what this query does you can experiment with a simpler SELECT statement:

    SELECT post_id,
           IF(meta_key='geo_lat',meta_value,NULL) lat,
           IF(meta_key='geo_lon',meta_value,NULL) lon
      FROM table_1
    

    What this does is to return a three column set, first is the ID, second column (named lat here) will bring the meta_value only if meta_key in the row is geo_lat, otherwise NULL. Third column is the same, but for geo_lon. It will generate a set like:

    +---------+---------+---------+
    | post_id | lat     | lon     |
    +---------+---------+---------+
    | 1       | 12.400  | NULL    |
    | 1       | NULL    | 123.000 |
    | 2       | 234.200 | NULL    |
    | 2       | NULL    | 4.200   |
    +---------+---------+---------+
    

    Then, with the use of GROUP_BY rows will be grouped when the ID is the same, and the values used on lat and lon will be decided by MAX. Since NULL is always "smaller", only non-null values will be selected effectifelly joining the rows into:

      SELECT post_id,
             MAX(IF(meta_key='geo_lat',meta_value,NULL)) lat,
             MAX(IF(meta_key='geo_lon',meta_value,NULL)) lon
        FROM table_1
    GROUP BY post_id
    
    +---------+---------+---------+
    | post_id | lat     | lon     |
    +---------+---------+---------+
    | 1       | 12.400  | 123.000 |
    | 2       | 234.200 | 4.200   |
    +---------+---------+---------+
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分