Select rows as columns for wordpress post meta

前端 未结 3 688
一生所求
一生所求 2021-02-09 13:59

WordPress\'s wp_postmeta table has all the additional fields for a post but they are in rows so it\'s easy to add more.

However, now I want to query for all

相关标签:
3条回答
  • 2021-02-09 14:23

    What about something like this?

    SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
    FROM wp_posts p
    LEFT JOIN wp_postmeta m1
        ON p.id = m1.post_id AND m1.meta_key = 'total_related'
    LEFT JOIN wp_postmeta m2
        ON p.id = m2.post_id AND m2.meta_key = 'updated'
    LEFT JOIN wp_postmeta m3
        ON p.id = m3.post_id AND m3.meta_key = 'cricket'
    

    And since you aren't looking for a specific post you should be able to do this.

    If you want to query specific post_types you can try something like this

    SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
    FROM wp_posts p
    LEFT JOIN wp_postmeta m1
        ON p.id = m1.post_id AND m1.meta_key = 'total_related'
    LEFT JOIN wp_postmeta m2
        ON p.id = m2.post_id AND m2.meta_key = 'updated'
    LEFT JOIN wp_postmeta m3
        ON p.id = m3.post_id AND m3.meta_key = 'cricket'
    WHERE p.post_type = 'my_custom_post_type';
    
    0 讨论(0)
  • 2021-02-09 14:23

    Try that:

    select post_title , 
     MAX(CASE WHEN `meta_key`='total_related' THEN meta_value END)as 'total_related',
     MAX(CASE WHEN `meta_key` = 'updated' THEN meta_value END) as 'updated' ,
     MAX(CASE WHEN `meta_key` = 'cricket' THEN meta_value END) as 'cricket' 
    FROM   wp_posts p 
    JOIN wp_postmeta m ON p.id = m.post_id 
    GROUP BY p.id
    
    0 讨论(0)
  • 2021-02-09 14:34

    There are several approaches.

    Here's an example of one way to get the specified result, using correlated subqueries in the SELECT list:

    SELECT p.post_title
         , ( SELECT m1.meta_value
               FROM wp_post_metadata m1
              WHERE m1.meta_key = 'total_related'
                AND m1.post_id = p.id
              ORDER BY m1.meta_key LIMIT 1
           ) AS `total_related`
         , ( SELECT m2.meta_value
               FROM wp_post_metadata m2
              WHERE m2.meta_key = 'updated'
                AND m2.post_id = p.id
              ORDER BY m2.meta_key LIMIT 1
           ) AS `updated`
         , ( SELECT m3.meta_value
               FROM wp_post_metadata m3
              WHERE m3.meta_key = 'cricket'
                AND m3.post_id = p.id
              ORDER BY m3.meta_key LIMIT 1
           ) AS `cricket`
      FROM wp_posts p
     WHERE p.id IN (5,8)
    

    There are several other approaches, each with its own advantages and drawbacks.

    There's a somewhat related question I referenced in a comment on the question. That question illustrates several approaches, but omits a correlated subquery approach.)

    0 讨论(0)
提交回复
热议问题