dongmoyu0336 2014-04-11 11:05
浏览 78
已采纳

如何在mysql for Wordpress数据库中将行值转换为列标题

Using the following query I have fetched results from wp_posts and wp_postmeta table.

SELECT a., b. FROM wp_posts a, wp_postmeta b WHERE a.ID = b.post_id AND a.post_status = 'publish' AND a.post_type='wpsc-product'

From the above result, I want to filter the results to one more stage

As you know wp_postmeta structure is like

meta_id | post_id | meta_key | meta_value

I want to make all the meta_key values of the result to column names and its corresponding value as its value.

For eg if the table is like:

Meta_id-----------post_id-----------meta_key-----------meta_value

1-----------------31--------------mk1----------------mv1

2-----------------31--------------mk2----------------mv2

3-----------------31--------------mk3----------------mv3

The expected result is:

Meta_id-----------post_id-----------mk1--------mk2---------mk3

1-----------------31-----------------mv1---------mv2---------mv3

Is this possible??? I want this along with my join query.

The formatting of question is not correct. Please forgive for that.

  • 写回答

2条回答 默认 最新

  • douzhe3516 2014-04-11 11:17
    关注

    You can use CASE if there are limited meta_keys

    SELECT a.*,b.Meta_id, b.post_id,
    CASE WHEN b.meta_key ='mk1' THEN b.meta_value END `mk1`,
    CASE WHEN b.meta_key ='mk2' THEN b.meta_value END `mk2`,
    CASE WHEN b.meta_key ='mk3' THEN b.meta_value END `mk3`
    FROM wp_posts a
    JOIN wp_postmeta b ON( a.ID = b.post_id )
    WHERE a.post_status = 'publish' 
    AND a.post_type='wpsc-product'
    AND b.meta_key IN('mk1','mk2','mk3')
    

    Edit for duplicates issue you can use JOINs

    SELECT p.*,
    a.Meta_id, 
    a.post_id,
    a.meta_value mk1, 
    b.meta_value mk2,
    c.meta_value mk3
    FROM wp_posts p  
    LEFT JOIN  wp_postmeta a ON(p.ID =a.post_id)
    JOIN  wp_postmeta b USING(post_id) /* is equal to ON(b.post_id = a.post_id) */
    JOIN  wp_postmeta c USING(post_id)
    WHERE a.meta_key = 'mk1'
    AND b.meta_key = 'mk2'
    AND c.meta_key='mk3'
    

    Fiddle Demo only for meta table

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题