mysql - 获取特定字段具有两个最高值的所有记录 - MySQL

标签 mysql limit

我想对结果添加限制,例如,只有那些在 votes 字段中具有两个最高值的记录才应该出现在结果中。

查询:

SELECT  `dev`.`user_id` ,  `dev`.`fullname` , COUNT(  `pom_votes`.`performer_id` ) AS votes
FROM  `pom_votes` 
INNER JOIN  `dev` ON  `pom_votes`.`performer_id` =  `dev`.`user_id` 
WHERE MONTH( pom_votes.created_at ) =1
AND YEAR( pom_votes.created_at ) =2017
GROUP BY  `performer_id` 
ORDER BY  `votes` DESC ,  `id` DESC 

输出:

user_id | fullname | votes
--------------------------
53      | test1    |  3  |
60      | test2    |  2  |
57      | test3    |  2  |
55      | test4    |  2  |
52      | test5    |  2  |
51      | test6    |  2  |
75      | test7    |  1  |
83      | test8    |  1  |
61      | test9    |  1  |
58      | test10   |  1  |

需要输出:

user_id | fullname | votes
--------------------------
53      | test1    |  3  |
60      | test2    |  2  |
57      | test3    |  2  |
55      | test4    |  2  |
52      | test5    |  2  |
51      | test6    |  2  |

解释:

在需要的输出中看到,我想要所有在 votes 字段中具有最多两个最高值的记录。

最佳答案

我在处理这两个单独的查询时得到了它:

查询 1:

select DISTINCT count(`pom_votes`.`performer_id`) as votes from `pom_votes` where MONTH(pom_votes.created_at) = 1 and YEAR(pom_votes.created_at) = 2017 group by `performer_id` order by `votes` desc, `id` desc LIMIT 2

查询 2:

select `dev`.`user_id`, `dev`.`fullname`, count(`pom_votes`.`performer_id`) as votes from `pom_votes` inner join `dev` on `pom_votes`.`performer_id` = `dev`.`user_id` where MONTH(pom_votes.created_at) = 1 and YEAR(pom_votes.created_at) = 2017 group by `performer_id` having votes in(RESULT OF QUERY 1) order by `votes` desc, `id` desc

可能不是完美的解决方案,但它确实有效。

关于mysql - 获取特定字段具有两个最高值的所有记录 - MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41717775/

相关文章:

mysql - WP : Get wp_post, wp_meta_value[contact] 特定术语 ID

php - Laravel Eloquent - 将请求保存、更新和删除到相关表中

MySQL 联合、连接和限制

c - Visual C 中有全局变量大小限制的解决方法吗?

sql - 如何在 Apache Derby 中删除有限数量的行

java - 如何在Java中设置Grpc连接最大限制?

mysql - 获取商品计数并连接表以显示商品客户详细信息

MySQL 插入...选择 #1054 错误

java - 如何用单一方法获得多用途结果?

mysql - mysql 的 CakePHP 限制是 20 没有我设置它。我如何删除此限制?