drz73366 2013-04-16 16:52
浏览 98
已采纳

如何使用按DESC排序的主键创建MySQL表并在插入新行后保持这种方式?

I need to create an InnoDB table that I will use to add data to and constantly fetch the most recent 10 rows added to it. To avoid having to do an ORDER BY with every SELECT query to get those last 10 rows, I would like to have the table itself ordered by the Primary Key in DESC order so that I can skip the ORDER BY entirely and just do a SELECT ... LIMIT 10, which should automatically pull the most recent 10 rows added to the table.

How can I do that? Is it as simple as adding ORDER BY [PRIMARYKEY] DESC to the CREATE TABLE query? Will the table continue to be sorted in DESC order even after INSERTing new rows?

  • 写回答

1条回答 默认 最新

  • dongshan4878 2013-04-16 17:30
    关注

    A RDBMS never provides any guarantees on the order of the rows in any of the tables it manages. The only way to get a specific order is to ask for one. For the case of MySQL, the rows happens to be sorted by the primary key in ascending order often time when that key is in auto increment mode, but it's not a guaranteed property.

    Use ORDER BY on your queries to get the desired result.

    On the other hand, the ordering will be faster if the primary key type is BTREE (which is the default on most engine).

    The sorting direction isn't yet used on MySQL 5.5.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作