![](/img/trans.png)
[英]In Mysql how to get records which for the same foreign key has all values showed up in a list for another col
[英]Get all the records which has two most highest values for a specific field - MySQL
我想在結果上添加限制,只有那些記錄應該出現在結果中,該結果具有兩個最高值的投票字段。
查詢:
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 |
說明:
看到所需的輸出,我想所有這一切對現場投票最多兩個最高值的記錄。
我得到了這兩個單獨的查詢:
查詢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
可能不是一個完美的解決方案,但它的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.