我很难用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
于此项目表格-1 当我使用ORDER BY点DESC然后看起来像表-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
这可能吗?请任何人帮助我。对我来说太难了。
答案 0 :(得分: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