dongxinpa3101 2015-01-15 20:31
浏览 7
已采纳

从wp的元值中获取平均数

i've creating following wordpress query which output which is counting the records. However all posts does also have a meta_key with the name betting_odds where the meta_value is something like 2.05, 3.30

how can i add the average values of this meta_key into following query?

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
  • 写回答

1条回答 默认 最新

  • dongshilve4392 2015-01-15 21:24
    关注

    This is a common challenge when retrieving data from a key/value store like wp_postmeta.

    The trick is to put both the post_id and the meta_key into the ON clause, like so.

    (It's also helpful to use table aliases (in this case posts, stat, odds, etc.) in WordPress queries because they get quite a bit more readable.

    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
    

    Do you see how we are LEFT JOINing the postmeta table twice, once for each meta value we need?? Do you see how the meta_key match criterion goes into the ON clause, not the WHERE clause? That's the pattern to pull meta values for posts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站