0

我正在为 mysql 查询而苦苦挣扎。请帮我。这是我的查询,我得到了正确的结果,但我需要在 mysql 中修改结果。

                SELECT  bu.username,
                    bg.id as goal_id,
                    br.id as reason_id,
                    (SELECT COUNT(test_reason_id) FROM test_rank WHERE test_reason_id = br.id) as point
                FROM
                    test_goal AS bg INNER JOIN test_reason AS br ON 
                    br.user_id=bg.user_id INNER JOIN test_user AS bu ON
                    br.user_id=bu.id
                WHERE
                    bg.id       =   br.test_goal_id
                GROUP BY
                    bg.id
                ORDER BY
                    point DESC

Tabble-1 当我使用 ORDER BY point DESC 时,我的实际表格看起来像这样,然后它看起来像Table-2

username     goal_id    reason_id   point
 khan           8            3        2
 john           6            9        5
 yoyo           5           21        4
 smith         11            6        5

表 2 我的结果集如下所示

username     goal_id    reason_id   point
 john           6            9        5
 smith         11            6        5
 yoyo           5           21        4
 khan           8            3        2

但我想要这样的结果集

username     goal_id    reason_id   point   rank
 john           6            9        5       1
 smith         11            6        5       2
 yoyo           5           21        4       3
 khan           8            3        2       4

这可能吗?请任何人都可以帮助我。这对我来说太难了。

4

1 回答 1

3

像这样添加一个行计数变量:

select a.*,  (@row := @row + 1) as rank
from (
      SELECT  bu.username,
                bg.id as goal_id,
                br.id as reason_id,
                (SELECT COUNT(test_reason_id) FROM test_rank WHERE test_reason_id = br.id) as point                   
            FROM
                test_goal AS bg INNER JOIN test_reason AS br ON 
                br.user_id=bg.user_id INNER JOIN test_user AS bu ON
                br.user_id=bu.id                    
            WHERE
                bg.id       =   br.test_goal_id
            GROUP BY
                bg.id
            ORDER BY
                point DESC
) a, (SELECT @row := 0) r

请参阅这个简化的 SQLFiddle 示例

于 2012-07-13T08:05:12.770 回答