我正在运行以下查询,试图获取大量帖子的数据和相关元数据:
SELECT wp_posts.post_title, wp_posts.post_date,
wp_posts.ID, wp_postmeta.post_id, wp_postmeta.meta_key
FROM wp_postmeta
INNER JOIN wp_posts
ON wp_postmeta.post_id=wp_posts.id
WHERE wp_posts.post_status = \'publish\'
LIMIT 5
返回以下内容:
Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta_key] => _edit_lock
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _wp_page_template
)
[2] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _edit_last
)
...
但现在我意识到我需要一个更复杂的查询,因为我想要的是以下内容:
Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta] => array(
\'_wp_page_template\' => \'home.php\',
\'_edit_last\' => 2015-11-11 08:44:54,
)
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta] => array(
\'_wp_page_template\' => \'home.php\',
\'_edit_last\' => 2015-11-11 08:44:54,
)
)
[2] => stdClass Object
(
[post_title] => About us
[post_date] => 2015-11-11 08:44:54
[ID] => 3
[post_id] => 3
[meta] => array(
\'_wp_page_template\' => \'home.php\',
\'_edit_last\' => 2015-11-11 08:44:54,
)
)
SO网友:CᴴᵁᴮᴮʸNᴵᴺᴶᴬ
对于任何一个绊倒在这里的人。。我通过以下操作解决了此问题:
(根据您的代码进行了调整)
SELECT wp_posts.post_title, wp_posts.post_date,
wp_posts.ID, wp_postmeta.post_id, wp_postmeta.meta_key,
GROUP_CONCAT(wp_postmeta.meta_key SEPARATOR \':\') AS meta_keys
FROM wp_postmeta
INNER JOIN wp_posts
ON wp_postmeta.post_id=wp_posts.id
WHERE wp_posts.post_status = \'publish\'
GROUP BY wp_postmeta.post_id
LIMIT 5
通过这样做
GROUP_CONCAT(wp_postmeta.meta_key SEPARATOR \':\') AS meta_keys
和
GROUP BY wp_postmeta.post_id
它创建了一个结果
meta_keys
然后可以在PHP中展开
:
$meta_keys = explode(\':\', $item->meta_keys);