2012-02-12 96 views
0

我的网站允许用户记录出价。每个出价都单独保存并关联到用户ID。用户可以拥有多个出价,这些出价用于合计显示在网站上的总体出价。mysql获取特定结果的行号

我想在sql中做的是返回用户总体出价的结果集的位置。

我使用的SQL低于但当我被命令使用该组出现问题 - 排序似乎恢复到默认的数据库命令,而不是由用户的总和出价金额:

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 

感谢如果有人知道这是可能的?

回答

1

您需要将行数递增了子查询。并把你的WHERE条件,否则你的子查询将对一个给定用户的所有产品的总和出价。

SET @rowcount = 0; 
SELECT @rowCount:[email protected]+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 
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 
0

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

SELECT @rownum:[email protected]+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;