Wordpress SUM自定义字段(相同帖子,不同列)

时间:2014-12-15 13:08:55

标签: mysql wordpress inner-join

我的SQL有问题。 我有一个自定义post_type(client_sales)与几个自定义字段(“销售”,“折扣”等) 我有超过9000个帖子,每天我有超过100个帖子。

所以我想只使用一个SQL查询来跟踪“销售”和“折扣”的总和。

function get_sum_from_custom_fields($posttype , $status, $fields){
    global $wpdb;

    foreach ($status as $key => $val) {
        $status[$key] = "p.post_status = '{$val}'"; 
    }
    $status = implode(" OR ", $status);

    $fields = is_array($fields) ? $fields : array($fields);

    $cols = array();
    $inners = array();

    foreach ($fields as $field) {

        $cols[] = "SUM(c_{$field}.meta_value) AS {$field}";

        $inners[] = "INNER JOIN ".$wpdb->postmeta." c_{$field}
            ON c_{$field}.post_id=p.ID
            AND c_{$field}.meta_key = '$field'";

    }
    $cols = implode(", ", $cols);
    $inners = implode(" ", $inners);

    $q ="SELECT 
    count(p.ID) AS 'count',
    $cols
    FROM 
        $wpdb->posts p
        $inners
    WHERE 1=1
        AND p.post_type = '$posttype'
        AND ($status)
        AND p.post_name NOT LIKE '%revision%' 
        AND p.post_name NOT LIKE '%autosave%'";
    echo "<pre>"; var_dump($q); echo "</pre>";
    return  $wpdb->get_results($q);

}

所以我们假设你使用这个函数:

$posttype = 'client_sales';
$status = array(
    'discount_used',
    'in-progress',
    'discount_in_coupon'
);
$data1 = get_sum_from_custom_fields($posttype, $status,'sale');
$data2 = get_sum_from_custom_fields($posttype, $status,'discount');
$data3 = get_sum_from_custom_fields($posttype, $status, array ('sale','discount'));

data1和data2是正确的,而data3在“sale”列中返回错误。

示例:

$data1 would be: counts = 5000, c_sale = 2000
$data2 would be: counts = 5000, c_discount = 60
$data3 returns : counts = 5000, c_sale = 1376, c_discount = 60

那么为什么我在data3上的“c_sales”有所不同?从2000年到另一个我不理解的数字是正确的(1376)?

对data3的查询是:

SELECT 
count(p.ID) AS 'count_client_sales',
SUM(c_montant_dachats.meta_value) AS montant_dachats, SUM(c_montant_de_remise.meta_value) AS montant_de_remise
FROM 
    wp_posts p
    INNER JOIN wp_postmeta c_montant_dachats
        ON c_montant_dachats.post_id=p.ID
        AND c_montant_dachats.meta_key = 'montant_dachats' INNER JOIN wp_postmeta c_montant_de_remise
        ON c_montant_de_remise.post_id=p.ID
        AND c_montant_de_remise.meta_key = 'montant_de_remise'
    WHERE 1=1
        AND p.post_type = 'client_sales'
        AND (p.post_status = 'discount_used' OR p.post_status = 'in-progress' OR p.post_status = 'discount_in_coupon')
        AND p.post_name NOT LIKE '%revision%' 
        AND p.post_name NOT LIKE '%autosave%'

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你非常接近正确的解决方案(这是非常好的,因为wp_postmeta可以正确使用颈部疼痛)。

但是你应该在查询中使用LEFT JOIN而不是INNER JOIN。当您使用INNER JOIN时,如果左侧的表格不匹配,则会从结果集中删除右侧表格中的行。我怀疑你有一些行sale postmeta而没有discount postmeta,反之亦然。