从两个表wordpress获取列行的总和

时间:2016-09-16 02:28:16

标签: php mysql wordpress

我需要从wordpress postmeta table获取一列中的特定行的总数。它就像php,mysql查询求和。但是我返回一个空数组。

这是我的代码:

global $wpdb;
$avg_ratings = 
"
    SELECT sum($wpdb->postmeta.meta_value) 
    AS TotalRating
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'review_rating'  
    AND $wpdb->posts.post_title = get_the_title() 
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->posts.post_type = 'reviews'
";
$avg_rating = $wpdb->get_results( $avg_ratings, OBJECT );

print_r($avg_rating);

我在WP_Query中运行此查询,因此会get_the_title()自动检索WP_query。我实际上想要平均review_rating元键值的评级

2 个答案:

答案 0 :(得分:0)

尝试

 $results = $wpdb->get_results( 
                        $wpdb->prepare("query", $some_parameter) 
                     );

答案 1 :(得分:0)

试试这个

global $wpdb;
$title = get_the_title();
$avg_ratings = 
"
SELECT sum($wpdb->postmeta.meta_value) 
AS TotalRating
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
AND $wpdb->postmeta.meta_key = 'review_rating'  
AND $wpdb->posts.post_title = '$title'
AND $wpdb->posts.post_status = 'publish' 
AND $wpdb->posts.post_type = 'reviews'
";
$avg_rating = $wpdb->get_results( $avg_ratings, OBJECT );

print_r($avg_rating);