我正在创建以下wordpress查询哪个输出正在计算记录。但是所有帖子都有一个名为betting_odds的meta_key,其中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
答案 0 :(得分:0)
从wp_postmeta
等键/值存储区检索数据时,这是一个常见的挑战。
诀窍是将post_id
和meta_key
放入ON
子句中,就像这样。
(在WordPress查询中使用表别名(在本例中为posts
,stat
,odds
等)也很有帮助,因为它们可以获得更多功能可读的。
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 JOIN
两次postmeta表,我们需要的每个元值一次?您是否了解meta_key
匹配条件如何进入ON
子句而不是WHERE
子句?这是为帖子提取元值的模式。