【问题标题】:Displaying last x rows of query with limit显示有限制的最后 x 行查询
【发布时间】:2015-12-19 17:50:01
【问题描述】:

我目前正在尝试查询表中 game_id 小于 1000058 且定义了 limit 的所有值。例如,如果我设置limit 3,我想按升序获取最后 3 行。我知道可以通过设置像limit 2, 3 这样的偏移量来完成,但我需要事先知道行号。假设我不知道行号,如何按升序显示query 的最后3 行? SQLFIDDLE

显示正确的值,但顺序是 DESC 而不是 ASC

SELECT * FROM games WHERE mature = true AND category_id = 1004 AND game_id < 1000058 ORDER BY game_id DESC LIMIT 3;

显示正确的值,但我需要知道偏移量的行号

SELECT * FROM games WHERE mature = true AND category_id = 1004 AND game_id < 1000058 ORDER BY game_id LIMIT 2,3;

仅按升序显示前三行

SELECT * FROM games WHERE mature = true AND category_id = 1004 AND game_id < 1000058 ORDER BY game_id LIMIT 3;

想要的结果

game_id    game_name     cat_id  mature     description                         published_date
-------    ------------  ------  ------     ---------------------------------   --------------
1000055    Battlefield4  1004    1          Published by EA Digital Illusions   2013-01-01  
1000056    Rainbow6      1004    1          Published by EUbisoft               2015-01-01
1000057    Destiny       1004    1          Published by Bungie                 2014-01-01

【问题讨论】:

    标签: mysql sql select sql-order-by


    【解决方案1】:

    您可以使用嵌套查询 - 内部查询按降序排列,这样您就可以限制前三场比赛,然后外部查询按升序对结果进行排序:

    SELECT   *
    FROM     (SELECT   * 
              FROM     games 
              WHERE    mature = true AND 
                       category_id = 1004 AND 
                       game_id < 1000058 
              ORDER BY game_id DESC
              LIMIT    3) t
    ORDER BY game_id ASC        
    

    【讨论】:

      【解决方案2】:

      我认为这就是你要找的我的朋友:

      SELECT * FROM (
          SELECT * FROM games 
          where game_id < 1000058 
            and mature = true 
            and category_id = 1004 
         ORDER BY game_id DESC
         LIMIT 3
      ) sub
      
      ORDER BY game_id ASC
      

      【讨论】:

      • 我认为您需要内部查询的限制语句而不是外部查询。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      相关资源
      最近更新 更多