2017-01-18 5 views
1

결과에 제한을 추가하고 싶습니다. 필드에 대해 가장 높은 값이 두 개인 결과가 있어야합니다.특정 필드에 대해 가장 큰 두 개의 값을 가진 모든 레코드를 가져옵니다. -

검색어 :

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 | 

설명 :

표의 가장 큰 두 값이있는 모든 레코드가 필요합니다. 필드.

답변

0

내가이 두 개의 개별 쿼리 작업을 가지고 :

질의 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 

완벽한 솔루션을하지 않을 수 있지만, 그것은 작동합니다.

관련 문제