我想获取一个给出主题最大正确答案的用户ID。以下是表结构。
id user_id question_id answered paper
1 1 1 0 sub1
2 2 1 1 sub1
3 3 1 1 sub1
4 1 2 1 sub1
5 2 2 1 sub1
6 3 2 0 sub1
我尝试使用sql来获取结果,但是无法弄清楚如何在这个sql中将“2”作为动态
SELECT `user_id` FROM `table`
WHERE `answered` =1 GROUP BY `paper`
HAVING Count( `answered` ) >2
得到了答案
select `user_id` FROM table
where answered = 1 GROUP BY paper,user_id
HAVING Count(answered) > = (SELECT count( * ) AS count FROM table
WHERE answered =1GROUP BY paper,user_id ORDER BY count DESC Limit 1)
答案 0 :(得分:0)
您可以尝试使用这样的动态SQL:
mysql> PREPARE stmt FROM
-> 'SELECT `user_id` FROM `table`
-> WHERE `answered` =1 GROUP BY `paper`
-> HAVING Count( `answered` ) > ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @num
最后
mysql> DEALLOCATE PREPARE stmt;
另一个选项是创建一个存储过程,您可以将数字(例如2)作为输入参数传递。
答案 1 :(得分:0)
试试这个
SELECT COUNT(answered) AS answers, user_id FROM `table` WHERE answered=1 GROUP BY user_id ORDER BY answers DESC LIMIT 1, 1