MySQL查询从WP_PostMeta行到列

时间:2014-12-03 02:39:48

标签: mysql wordpress

我正在尝试从wordpress表wp_postmeta进行查询 我需要下面图片中_form_id_sub_id的数据。 我正在使用这个sql

SELECT meta_value,
MAX(CASE WHEN meta_key = '_field_14' THEN meta_value END) as a1,
MAX(CASE WHEN meta_key = '_field_15' THEN meta_value END) as a2,
MAX(CASE WHEN meta_key = '_field_17' THEN meta_value END) as a3,
MAX(CASE WHEN meta_key = '_field_18' THEN meta_value END) as a4
FROM wp_postmeta
Group by post_id

但是a1到a4上的NULL数据仍会显示在结果上。 我的SQL Fiddel 请指教,谢谢

enter image description here

预期结果 expected result

1 个答案:

答案 0 :(得分:2)

您需要选择post_idgroup by中不存在meta_value,因此您将从每个帖子中获得随机值

此外,只有帖子54,56,57具有这些字段,因此其余帖子将获得NULL值。

SELECT post_id,
                MAX(CASE WHEN meta_key = '_field_14' THEN meta_value  END) as a1,
                MAX(CASE WHEN meta_key = '_field_15' THEN meta_value  END) as a2,
                MAX(CASE WHEN meta_key = '_field_17' THEN meta_value  END) as a3,
                MAX(CASE WHEN meta_key = '_field_18' THEN meta_value  END) as a4
                FROM wp_postmeta
                Group by post_id

编辑:

根据结果,您只需要来自所有具有值的帖子的元值,您可以使用子查询和合并来获得您想要的内容

SELECT * FROM
(
SELECT 
       MAX(CASE WHEN meta_key = '_field_14' THEN meta_value END) as a1,
       MAX(CASE WHEN meta_key = '_field_15' THEN meta_value END) as a2,
       MAX(CASE WHEN meta_key = '_field_17' THEN meta_value END) as a3,
       MAX(CASE WHEN meta_key = '_field_18' THEN meta_value END) as a4
FROM wp_postmeta
Group by post_id
)T
where coalesce(a1,a2,a3,a4) is not null