V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
caixiexin
V2EX  ›  MySQL

请教一下 MySQL 中 order by ... limit offset,n 排序的问题

  •  
  •   caixiexin · 2017-03-17 11:58:52 +08:00 · 4104 次点击
    这是一个创建于 2568 天前的主题,其中的信息可能已经有所发展或是发生改变。

    说来惭愧,最近才知道 MySQL 中 order by ... limit offset,n 和不带 limit 的 order by 查询出来的排序结果是不一样的, order by ... limit offset,n 只对 前 n 条排序。

    可是看完官网文档后有个疑问: limit 难道不是总在 order by 之后吗? 只对部分数据排序再分页的话,难道不会出现翻页的时候前几页的数据出现在后几页?

    还是我英语不好,官网的文档理解错了?
    这边是官网的文档:
    https://dev.mysql.com/doc/refman/5.6/en/limit-optimization.html

    4 条回复    2017-04-16 16:15:18 +08:00
    gejun123456
        1
    gejun123456  
       2017-03-17 12:39:50 +08:00 via Android   ❤️ 1
    他说的排序结果不一样应该指的是相同值的行的顺序可能会不一样,可以看网页最下面例子,另外 limit orderby 是不需要全部排序的,找出最小的 limit 数据即可, orderby limit 这个应该是没有问题的。
    mingyun
        2
    mingyun  
       2017-03-17 23:42:23 +08:00   ❤️ 1
    赞同一楼,当某个排序字段有相同值的时候排序会出错,可以加上主键 id 再排序
    smilejava
        3
    smilejava  
       2017-04-16 16:12:20 +08:00
    引用: If multiple rows have identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan. In other words, the sort order of those rows is nondeterministic with respect to the nonordered columns.
    smilejava
        4
    smilejava  
       2017-04-16 16:15:18 +08:00
    引用: If multiple rows have identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan. In other words, the sort order of those rows is nondeterministic with respect to the nonordered columns.
    楼主的疑问应该是这段话吧?说的是如果排序字段如果具有相同的值, mysql server 按任意顺序来返回这些行,和一楼说的一致。
    order by + limit 先排序,再取 limit ,这个很好验证,写个 sql 就行验证结果了,可以多验证自己的疑问
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   952 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:28 · PVG 05:28 · LAX 14:28 · JFK 17:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.