简体   繁体   中英

Get all the records which has two most highest values for a specific field - MySQL

I want to add restrictions on the result like, only those records should appear in the result which has two most highest value for votes field.

Query:

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 

Output:

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  |

Needed output:

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

Explanation:

See in the needed output, I want all the records which has most two highest values for votes field.

I got it working with this two separate queries:

Queries 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

Queries 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

Might not be the perfect solution, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM