取决于最高计数我想获得每个用户的排名。
以下是查询:
SELECT @a:=@a+1 serial_number, `tbl_users`.`user_id`,
`tbl_users`.`first_name`,
`tbl_users`.`last_name`,
COUNT(`tbl_qa_questions`.`question_id`) AS qs_count
FROM `tbl_qa_questions`
LEFT JOIN `tbl_users`
ON `tbl_qa_questions`.`user_id` = `tbl_users`.`user_id`
, (SELECT @a:= 0) AS a
WHERE 1 AND DATE(`tbl_qa_questions`.`post_date`) BETWEEN '2015-01-01' AND '2015-01-19'
AND `tbl_qa_questions`.`status` = 1
GROUP BY `tbl_qa_questions`.`user_id`
ORDER BY qs_count DESC LIMIT 5
显示结果
serial_number user_id first_name last_name qs_count
10 47 Sourav Sen 26
11 32 Alan Donald 15
9 587 Abraham Harrison 2
8 586 Thomas Broad 2
6 13 Sumanta Sen 2
但它应该:
serial_number user_id first_name last_name qs_count
1 47 Sourav Sen 26
2 32 Alan Donald 15
3 587 Abraham Harrison 2
4 586 Thomas Broad 2
5 13 Sumanta Sen 2
.
.
.
29 14 xyz Sen 2
30 15 abc Sen 2
31 16 cdf Sen 2
即。每行的序列号应为1,2,3,4和5。
答案 0 :(得分:2)
只需在外部查询中添加编号,即可嵌套聚合。问题是变量在 GROUP BY
开始之前会增加,因此您会得到一些随机结果。实际上,当在SELECT中使用不在GROUP BY中的东西时,总是如此,特定于MySQL(其他DB只会给你错误)。
SELECT @a:=@a+1 serial_number, aa.* from (
sELECT
`tbl_users`.`first_name`,
`tbl_users`.`last_name`,
COUNT(`tbl_qa_questions`.`question_id`) AS qs_count
FROM `tbl_qa_questions`
LEFT JOIN `tbl_users`
ON `tbl_qa_questions`.`user_id` = `tbl_users`.`user_id`
, (SELECT @a:= 0) AS a
WHERE 1 AND DATE(`tbl_qa_questions`.`post_date`) BETWEEN '2015-01-01' AND '2015-01-19'
AND `tbl_qa_questions`.`status` = 1
GROUP BY `tbl_qa_questions`.`user_id`
ORDER BY qs_count DESC LIMIT 5
) aa