Mysql:获取N个记录的给定子集的n个元素

时间:2014-10-26 19:08:52

标签: mysql sql database

我的目标是从表的N个寄存器的给定子集中获取n个“最佳”项。我有一个名为食谱的表,我想要获得最后5个最好的食谱(最喜欢的),比方说,上传了50个食谱。 只是为了澄清,它会是这样的:

SELECT * FROM `recipes` 
WHERE id IN 
    (SELECT id FROM `recipes` ORDER BY created DESC LIMIT 50) 
ORDER BY likes DESC LIMIT 5

但LIMIT不能用于子查询。那么,实现这一目标的最简单方法是什么?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用联接

执行相同的操作
  SELECT * FROM `recipes`  R1
 JOIN 
(SELECT id FROM `recipes`      ORDER BY created DESC LIMIT 50) R2
 ON R1.id =R2.id
 ORDER BY R1.likes DESC LIMIT 5

答案 1 :(得分:1)

您可以在没有join的情况下完成您的工作:

SELECT r.*
FROM (SELECT r.*
      FROM recipes
      ORDER BY created DESC
      LIMIT 50 
     ) r
ORDER BY likes DESC
LIMIT 5;