在WordPress数据库查询中加入/汇总自定义字段

时间:2015-05-22 20:14:36

标签: mysql wordpress advanced-custom-fields

尽管谷歌搜索了2个小时并尝试了各种JOINS和UNIONS和ALIASES以及诸如此类的东西,我仍然无法在一个表中检索来自WordPress数据库的wp_postmeta表中的两个子查询的结果(我甚至都没有在这里关心wp_posts,我感兴趣的所有数据都在postmeta中。

我有自定义字段(使用ACF插件管理),在数据库中看起来如下所示,其中一个键用于区域,另一个键用于数值。

|   ID   |   meta_key           |   meta_value   |
|   1    |   group_name         |   Japan        |
|   1    |   facility_index     |   0.83         |
|   2    |   group_name         |   USA          |
|   2    |   facility_index     |   4.51         |

我需要一个返回以下内容的查询,以便我可以按区域计算聚合(例如,所有工具的facility_index的总和,按国家/地区,即按group_name):

|   ID   |   group_name  |   facility_index   |
|   1    |   Japan       |   0.83             |
|   2    |   USA         |   4.51             |

此查询列出了group_name两次,而不是列出第3列中的facility_index:

SELECT post_id, meta_value, result2.meta_value FROM
(
(
SELECT post_id, meta_value
FROM wp_postmeta
WHERE meta_key = "group_name"
)
UNION
(
SELECT post_id, meta_value
FROM wp_postmeta
WHERE meta_key = "facility_index"
)
) AS result2
GROUP BY post_id

编辑以显示完全符合我想要的最终查询,这要归功于下面接受的答案:

SELECT
  meta1.meta_value AS group_name,
  meta2.meta_value AS facility_index,
  SUM(meta2.meta_value) AS 'fac_index_geo' 
FROM wp_posts post
  LEFT JOIN wp_postmeta meta1 ON meta1.post_id = post.ID AND meta1.meta_key = 'group_name'
  LEFT JOIN wp_postmeta meta2 ON meta2.post_id = post.ID AND meta2.meta_key = 'facility_index'
WHERE
  post.post_type = 'facility'
  GROUP BY group_name

1 个答案:

答案 0 :(得分:2)

据我所知,您正在寻找自定义SQL查询 - 即您不想使用WP_Query对象。

为此我会使用一些JOINS而不是子查询。 另外,我建议您查询post_type,否则您可能会从自动保存/修订或类似的错误结果中获取数据。     

/*
INNER JOIN
This query will only return posts that contain all meta values
i.e. all 'post' items with group_name AND facility_index
*/
$sql = "
SELECT
  post.ID,
  meta1.meta_value AS group_name,
  meta2.meta_value AS facility_index
FROM {$wpdb->posts} post
  INNER JOIN {$wpdb->postmeta} meta1 ON meta1.post_id = post.ID AND meta1.meta_key = 'group_name'
  INNER JOIN {$wpdb->postmeta} meta2 ON meta2.post_id = post.ID AND meta2.meta_key = 'facility_index'
WHERE
  post.post_type = 'post'
";

$data = $wpdb->get_results( $sql );

只需确保更新post_type条件以匹配您所需的帖子类型。

或者,如果您还想获得缺少元值的帖子,可以使用此查询

/* 
LEFT JOIN
This query will return all posts even if they have missing meta values
i.e. if group_name or facility_index is empty, then NULL is returned in the column
*/
$sql = "
SELECT
  post.ID,
  meta1.meta_value AS group_name,
  meta2.meta_value AS facility_index
FROM {$wpdb->posts} post
  LEFT JOIN {$wpdb->postmeta} meta1 ON meta1.post_id = post.ID AND meta1.meta_key = 'group_name'
  LEFT JOIN {$wpdb->postmeta} meta2 ON meta2.post_id = post.ID AND meta2.meta_key = 'facility_index'
WHERE
  post.post_type = 'post'
";