mysql获取特定结果的行号

时间:2012-02-12 18:04:29

标签: mysql group-by sql

我的网站允许用户录制出价。每个出价都会单独保存并与用户ID相关联。用户可以有多个出价,用于累计在网站上显示的一个总出价。

我在sql中尝试做的是返回用户整体出价来自结果集的位置。

我正在使用的sql在下面但是当我使用group by命令时出现问题 - 排序似乎恢复到默认的db顺序而不是用户出价金额的总和:

SET @rowcount = 0;
SELECT rowCount, userId FROM (
    SELECT userId, @rowcount := @rowcount + 1 as rowCount, sum(amount) as amount FROM bids group by userId order by amount desc
 ) t when product = xxxxx

感谢是否有人知道这是否可行?

3 个答案:

答案 0 :(得分:1)

您需要将rowcount增量移出子查询。并将WHERE条件置于其中,否则您的子查询将对给定用户的所有产品的出价进行总结。

SET @rowcount = 0;
SELECT @rowCount:=@rowcount+1 as rowcount, userId, amount FROM 
 (
    SELECT userId, sum(amount) as amount 
    FROM bids 
    WHERE product = xxxxx 
    GROUP BY userId 
    ORDER BY amount DESC
 ) t 

答案 1 :(得分:0)

你有没试过?

SET @rowcount = 0;
SELECT rowCount, userId FROM (
    SELECT userId, @rowcount := @rowcount + 1 as rowCount from 
     (select sum(amount) as amount, userId FROM bids group by userId) s
     order by s.amount desc
 ) t where product = xxxxx

答案 2 :(得分:0)

如果我理解正确,你可以尝试这样的事情:

SELECT @rownum:=@rownum+1 ‘rank’, userId FROM (SELECT product, userId, sum(amount) AS amount FROM bids GROUP BY userId) t, (SELECT @rownum:=0) r WHERE t.product = xxxx ORDER BY t.amount DESC;