获取前N行,包括绑定值MYSQL

时间:2016-10-02 22:12:32

标签: mysql database

+-----+-------+-----+
| id  | Name  |Votes|
+-----+-------+-----+
|  3  | Mark  | 42  |
|  6  | Shawn | 39  |
|  1  | Joe   | 36  |
|  5  | Jay   | 36  |
+-----+-------+-----+

对于这个例子,我想要的是检索前3个最高票数的行。但是,如果您注意到,则有两行具有相同的投票计数。所以这应该是结果:

{{1}}

如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

您必须使用自己的表格执行INNER JOIN。首先,您要选择前3个唯一/不同分数,这可以通过使用:

来完成
SELECT DISTINCT Votes FROM mytable ORDER BY Votes DESC LIMIT 3

现在您已获得前3个分数,您想将其加入原始表:

SELECT t1.* FROM mytable AS t1
INNER JOIN
  (SELECT DISTINCT Votes FROM mytable ORDER BY Votes DESC LIMIT 3) AS topvotes
ON
  topvotes.Votes = t1.Votes
ORDER BY t1.Votes DESC

请参阅策略的简单图表:

INNER JOIN strategy

要使此查询有效,您需要索引Votes列,以便子查询可以快速删除不同的投票;)

这是一个概念验证SQLfiddle:http://sqlfiddle.com/#!9/c78f0/10

答案 1 :(得分:1)

可能效率不高,但我认为这应该有效:

SELECT * FROM scores WHERE score IN(SELECT score FROM scores ORDER BY score DESC LIMIT 3)

虽然这会产生关于子查询中不支持限制的错误。

解决方法;

SELECT * FROM scores WHERE score IN(SELECT * FROM (SELECT score FROM scores ORDER BY score DESC LIMIT 3) AS t)