我有一个包含category
和votes
列的表格。我以前尝试过多种解决方案但收效甚微;通常会发生的是,不是返回每个类别中的前3个项目,而是返回所有可用项目。
SELECT `id`, `user_id`, `full_name`, `category`, `year`, `month`, `thumbnail_photo`, `photo_title`, `votes`
FROM
(
SELECT `id`, `user_id`, `full_name`, `category`, `year`, `month`, `thumbnail_photo`, `photo_title`, `votes`,
@category_rank := IF(@current_category = category, @category_rank + 1, 1) AS category_rank,
@current_category := category
FROM `photo_contest`
ORDER BY
`category`,
`votes` DESC
) ranked
WHERE
category_rank <= 3
AND `year` = '2017'
AND `month` = 'April'
AND `votes` > 0
此特定解决方案改编自SQLines。我最终想做的是转一个这样的表:
Name | Category | Votes
--------- | -------- | -----
Name Foo | CatFoo | 0
Name Bar | CatFoo | 1
Name Baz | CatFoo | 10
Name Quux | CatFoo | 200
Name ooF | CatBar | 50
Name raB | CatBar | 300
Name zaB | CatBar | 10
Name xuuQ | CatBar | 200
...为:
Name | Category | Votes
--------- | -------- | -----
Name Quux | CatFoo | 200
Name Baz | CatFoo | 10
Name Bar | CatFoo | 1
Name raB | CatBar | 300
Name xuuQ | CatBar | 200
Name ooF | CatBar | 50
...包含其他WHERE语句。年,月和最低票数。
答案 0 :(得分:1)
您的子查询尝试计算整个表的排名。如果您只想使用投票&gt;对所选年份进行排名0,您应该将这些条件作为自己的WHERE条件复制到子查询中。
更新:
看起来外部查询中缺少导致上述问题的struct IconSizes {
var typesList: Array<String>
var iphone: [Dictionary<String, Any>]
init() {
self.typesList = ["iPhone"]
self.iphone = [
["size":16,"name":"icon_small.png"],
["size":32,"name":"icon_small@2x.png"],
["size":32,"name":"icon_medium.png"],
["size":64,"name":"icon_medium@2x.png"],
["size":64,"name":"icon_large.png"],
["size":128,"name":"icon_large@2x.png"],
["size":128,"name":"icon.png"],
["size":256,"name":"icon@2x.png"]
]
}
}
。我在sqlfiddle创建了以下DDL / SQL。
ORDER BY
答案 1 :(得分:0)
我不是MySQL的专家,所以我建议你使用不同的(标准SQL)方法:你可以在Category
和Votes
上加入表格,使其更少或相同到当前行的投票。
select t1.Name, t1.Category, t1.Votes, count(distinct t2.Name) as rank
from photo_contest t1
join photo_contest t2
on t1.Category = t2.Category and
t1.Votes <= t2.Votes
/*where whatever you want*/
group by t1.Name, t1.Category, t1.Votes
having count(distinct t2.Name) <= 3
order by t1.Category, rank
我测试了它here,它似乎做了你要求的
答案 2 :(得分:0)
听起来您的PHPMyAdmin需要升级或替换。同时你可能想尝试@Stefano Zanini的非MySQL特定SQL:
SELECT
t1.`id`, t1.`category`, t1.`year`, t1.`month`,
t1.`votes`, count(distinct t2.`id`) as rank
FROM photo_contest t1
INNER JOIN photo_contest t2 ON
t1.`category` = t2.`category` AND
t1.`votes` <= t2.`votes`
WHERE t1.`votes` > 0
GROUP BY t1.`id`, t1.`category`, t1.`votes`
HAVING count(distinct t2.`id`) <= 3
ORDER BY t1.`category`, rank;
可在sqlfiddle上找到。如果您认为此解决方案更适合您,请将@Stefano Zanini的答案归功于此答案。