WordPress的wp_postmeta
表包含帖子的所有其他字段,但它们是行,因此可以轻松添加更多字段。
但是,现在我想查询所有帖子的所有字段,我很明显地希望列中的那些字段而不是一行。
这是我正在运行的查询
SELECT p.post_title,
m.meta_value,
m.meta_key
FROM wp_posts p
JOIN wp_postmeta m
ON p.id = m.post_id
WHERE p.id = 72697;
这将为我提供所有meta_values及其各自的元键作为列。但我需要将元键值作为列,将元值作为行
例如,meta_key
可以是additional_description
,其值可以是What's up
所以我需要这样的东西
SELECT p.post_title, additional_description
FROM wp_posts p
JOIN wp_postmeta m
ON p.id = m.post_id
WHERE p.id = 72697;
我需要它作为专栏。我还需要所有帖子,而不是特定的帖子,但每当我删除where
时,它都不会查询(我有很多帖子,这可能是一个问题)。
以下是一些示例数据以及我希望结果显示的方式 wp_postmeta表
meta_key post_id meta_key meta_value
1 5 total_related 5
2 5 updated 0
3 5 cricket 1
4 8 total_related 8
5 8 updated 1
6 8 cricket 0
wp_post table
id post_title other things I dont care about
5 This is awesome
8 This is more awesome
wp_post id与wp_postmeta表
上的post_id有关想要的结果
post_title total_related updated cricket
This is awesome 5 0 1
This is more awesome 8 1 0
答案 0 :(得分:7)
这样的事情怎么样?
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'
由于你不是在寻找特定的帖子,你应该能够做到这一点。
如果您想查询特定的post_types
,可以尝试这样的
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';
答案 1 :(得分:2)
有几种方法。
以下是使用SELECT列表中相关子查询获取指定结果的一种方法示例:
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)
还有其他几种方法,每种方法都有自己的优点和缺点。
在我对这个问题的评论中引用了一个有点相关的问题。这个问题说明了几种方法,但省略了相关的子查询方法。)
答案 2 :(得分:2)
试试:
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