在MySQL查询上创建一个排名列

时间:2013-05-14 11:21:23

标签: mysql wordpress

我有一个MySQL查询,我想添加一个列来根据用户的平衡对用户进行排名。查询是:

SELECT (display_name) 'Author',
IFNULL(ROUND(SUM(balance.meta_value),2),2) 'Balance',
IFNULL(ROUND((((SUM(balance.meta_value+bet.meta_value)-                                                         
SUM(bet.meta_value))/SUM(bet.meta_value))*100),2),2) 'Yield %'
FROM wp_posts p
 JOIN wp_users u 
ON p.post_author = u.ID
 LEFT JOIN wp_postmeta bet 
ON p.ID = bet.post_id AND bet.meta_key = 'bet'
LEFT JOIN wp_postmeta balance 
ON p.ID = balance.post_id AND balance.meta_key = 'balance'
WHERE p.post_status = 'publish'
GROUP BY u.ID
ORDER BY Balance DESC

我尝试添加SET @rownum := 0; and @rownum := @rownum + 1 AS等级,但它不起作用,排名没有按最高余额排序。

有人能帮助我吗?感谢。

1 个答案:

答案 0 :(得分:3)

select *, @rownum := @rownum + 1 from
(
SELECT (display_name) 'Author',
    IFNULL(ROUND(SUM(balance.meta_value),2),2) 'Balance',
    IFNULL(ROUND((((SUM(balance.meta_value+bet.meta_value)-SUM(bet.meta_value))/SUM(bet.meta_value))*100),2),2) 'Yield %'
FROM wp_posts p
JOIN wp_users u 
    ON p.post_author = u.ID
LEFT JOIN wp_postmeta bet 
    ON p.ID = bet.post_id AND bet.meta_key = 'bet'
LEFT JOIN wp_postmeta balance 
    ON p.ID = balance.post_id AND balance.meta_key = 'balance'
WHERE p.post_status = 'publish'
GROUP BY u.ID
ORDER BY Balance DESC
)x, (select @rownum := 0) r