Sql query to exclude meta_value where meta_key = x on SUM for WooCommerce

You can also use 2 INNER JOIN for the same table with a different reference as following (to avoid a double query like in your answer):

global $wpdb;

return $wpdb->get_var( "
    SELECT SUM(pm.meta_value)
    FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
    INNER JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
    WHERE p.post_type = 'shop_order'
    AND p.post_status IN ('wc-processing','wc-completed')
    AND pm.meta_key = '_order_total'
    AND pm2.meta_key = '_billing_first_name' 
    AND pm2.meta_value != 'abc'
" );

Tested and works smoother.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top