对于某些背景,我之前询问过retrieving sets with highest number of combined votes among objects。这对于获得前25名非常有用,但现在我想得到排名前10%,按排名的时间戳排序。以下是有问题的表格:
CREATE TABLE IF NOT EXISTS `rankset` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` TEXT NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `item` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) NOT NULL ,
`rankset` BIGINT NOT NULL ,
`image` VARCHAR(45) NULL ,
`description` VARCHAR(140) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `mydb`.`vote` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`value` TINYINT NOT NULL ,
`item` BIGINT NOT NULL ,
`user` BIGINT NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
我列出了迄今为止我尝试过的内容,但老实说,我甚至不知道从哪里开始。这是SQL小提琴:
答案 0 :(得分:1)
来自评论:
看看这个答案:https://stackoverflow.com/a/4474389/97513,他为他的项目排名生成一个列,使用WHERE子句使用rank <= (SELECT COUNT(1) / 10 FROM rankset)
来识别前10%。
我整理了一个SQL小提琴来演示:http://sqlfiddle.com/#!2/fe315/21 - 这是另一个有更多结果的内容,因此当您添加更多行时,您可以看到它向上扩展:http://sqlfiddle.com/#!2/a02ea/1
使用的SQL:
SET @rn := 0;
SELECT (@rn:=@rn+1) AS rank, q.*
FROM (
SELECT rankset.*, COALESCE(COUNT(vote.id), 0) AS votes
FROM rankset, vote, item
WHERE item.rankset = rankset.id
AND vote.item = item.id
GROUP BY rankset.id
ORDER BY votes DESC
) q
WHERE
@rn <= (SELECT COUNT(1)/10 FROM rankset);