• Resolved leaklords

    (@kwark)


    Hi,

    I search to create a $wpdb query for a sum of meta_value where each post have this meta_key->meta_value pair. But I need to have in the final result the sum of this meta_value where the total is filtered by posts-categories. And the result is displaying in administration.

    The result must be something like

    cat_name1 -> sum (meta_value(s))
    cat_name2 -> sum (meta_value(s))
    cat_name3 -> sum (meta_value(s))

    I think INNER JOIN is the solution but I’m not an expert with mysql, INNER JOIN,… to create this request.

    Any help is great appreciate.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter leaklords

    (@kwark)

    It’s not the subject but I have builded another option with SELECT meta_key, sum(meta_value) AS my_total FROM $wpdb->postmeta WHERE meta_key=%s GROUP BY meta_key

    but to group the sum(meta_value) from this meta_key (placed in all posts) foreach categories I have difficulties.

    Thread Starter leaklords

    (@kwark)

    If a user comes here, after studies and some tries I have this. But currently this solution don’t exclude the “links” taxonomy.

    $meta_key = 'your_meta';
    
    $request = $wpdb->get_results($wpdb->prepare(
    "
    SELECT sum(meta_value) AS total, name 
    
    FROM $wpdb->postmeta AS pm, $wpdb->posts AS p, $wpdb->term_relationships AS tr, $wpdb->terms AS t 
    
    WHERE pm.post_id=p.ID
    AND p.post_status='publish'
    AND pm.post_id=tr.object_id
    AND tr.term_taxonomy_id=t.term_id
    AND meta_key=%s
    GROUP BY t.name
    ",
    $meta_key));

    INNER JOIN, LEFT JOIN, JOIN, RIGHT JOIN,… is a “new” more clear/flexible clause recommended in replacement of WHERE (nothing else).

    Thread Starter leaklords

    (@kwark)

    Only the total sum of a meta_key -> value pair placed in multiple posts with taxonomy relation “category” only.

    $meta_key = 'your_meta';
    
    $request = $wpdb->get_results($wpdb->prepare(
    "
    SELECT sum(meta_value) AS total, name 
    
    FROM $wpdb->postmeta AS pm, $wpdb->posts AS p, $wpdb->term_relationships AS tr, $wpdb->term_taxonomy AS tt, $wpdb->terms AS t 
    
    WHERE pm.post_id=p.ID AND p.post_status='publish'
    AND pm.post_id=tr.object_id
    AND tr.term_taxonomy_id=tt.term_taxonomy_id
    AND tt.taxonomy='category'
    AND tr.term_taxonomy_id=t.term_id
    AND meta_key=%s
    GROUP BY t.name
    ORDER BY total DESC
    ",
    $meta_key));
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Any Mysql guru to help me please to retrieve a sum of meta_value’ is closed to new replies.