简体   繁体   中英

How to get rank using mysql query with PHP

I have the following code, and I would like to get only the league rank of the user based on his total balance. How can I do this?

// Set League Rank by User
global $post;
$post_author = $post->post_author;
$post_status = 'publish';
$meta_key = 'balance';
$rank = $wpdb->get_var( $wpdb->prepare(
    "
    SELECT *, @rownum := @rownum + 1 from
    (
    SELECT 
        SUM(meta_value) as balance, 
    FROM {$wpdb->postmeta} pm
    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
    JOIN    (SELECT @curRow := 0) r;
    WHERE pm.meta_key = %s AND p.post_author = %s AND p.post_status = %s
    order by balance desc)x, (SELECT @rownum := 0) r
    ",
    $meta_key, $post_author, $post_status
    ) );

Can some help me?

Thank you.

Try something like that:

SELECT 
    ROUND (SUM(meta_value),2) as balance, 
    @curRow := @curRow + 1 AS rank
FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
JOIN    (SELECT @curRow := 0) r;
WHERE pm.meta_key = %s AND p.post_author = %s AND p.post_status = %s
order by balance desc

I might misunderstood what do you mean by rank so if this doesn't work, please explain further what exactly do you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM