从 wp 中的元值获取平均数

Getting the average number from a meta value in wp

我创建了以下 wordpress 查询,其输出正在计算记录。但是,所有帖子也确实有一个 meta_key,名称为 betting_odds,其中 meta_value 类似于 2.05、3.30

如何将此 meta_key 的平均值添加到以下查询中?

SELECT count(DISTINCT $wpdb->postmeta.`post_id`) 
  FROM $wpdb->posts
       LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
       LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
       LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) 
 WHERE $wpdb->postmeta.meta_key       = 'betting_status'
    AND $wpdb->postmeta.meta_value    != 'Ikke afgjort'
    AND $wpdb->posts.post_status      = 'publish'
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->term_taxonomy.term_id  = 106

wp_postmeta 等 key/value 存储检索数据时,这是一个常见的挑战。

诀窍是将 post_idmeta_key 都放入 ON 子句中,就像这样。

(在 WordPress 查询中使用 table 别名(在本例中为 postsstatodds 等)也很有帮助,因为它们非常有用更具可读性。

SELECT count(DISTINCT posts.ID), AVG(odds.meta_value)
  FROM $wpdb->posts posts
  LEFT JOIN $wpdb->postmeta stat
                 ON posts.ID = stat.post_id
                AND stat.meta_key = 'betting_status'
  LEFT JOIN $wpdb->postmeta odds
                 ON posts.ID = odds.post_id
                AND odds.meta_key = 'betting_odds'
  LEFT JOIN $wpdb->term_relationships tr ON posts.ID = tr.object_id
  LEFT JOIN $wpdb->term_taxonomy t ON tr.term_taxonomy_id = t.term_taxonomy_id 
 WHERE stat.meta_value    != 'Ikke afgjort'
   AND posts.post_status      = 'publish'
   AND t.taxonomy = 'category'
   AND t.term_id  = 106

你看到我们是如何 LEFT JOINing postmeta table 两次的吗,一次针对我们需要的每个元值?您是否看到 meta_key 匹配条件如何进入 ON 子句,而不是 WHERE 子句?这是为帖子提取元值的模式。