如何使用PHP使用mysql查询获得排名

时间:2013-05-14 15:05:30

标签: php mysql wordpress

我有以下代码,我想根据他的总余额获得用户的联赛排名。我怎么能这样做?

// 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
    ) );

有人可以帮助我吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试类似的东西:

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

我可能会误解你的等级是什么意思,如果这不起作用,请进一步解释你究竟需要什么。