Select rows as columns for wordpress post meta

前端 未结 3 689
一生所求
一生所求 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: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.)

提交回复
热议问题