V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ASpiral
V2EX  ›  问与答

求教: mysql 中 select 和 order by 的执行顺序

  •  
  •   ASpiral · 2020-03-23 11:21:49 +08:00 · 950 次点击
    这是一个创建于 1512 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一直以为 mysql 中 select 先于 order by 执行,但最近项目中遇到了问题发现并不是这样;
    对问题做了下简化:表 t1 中有列 id,列中有 3 行数据[1, 2, 3]

    # 输入
    select id, @n:=@n+10 rank from t1, (select @n:=0) t2 order by rank desc;
    # 输出
    +------+------+
    | id   | rank |
    +------+------+
    |    3 |   30 |
    |    2 |   20 |
    |    1 |   10 |
    +------+------+
    # 输入
    select id, @n:=@n+10 rank from t1, (select @n:=0) t2 order by id desc;
    # 输出
    +------+------+
    | id   | rank |
    +------+------+
    |    3 |   10 |
    |    2 |   20 |
    |    1 |   30 |
    +------+------+
    

    第一条 sql 按 rank 排序由于 rank 是 select 后才有的所以 select 先于 order by 执行,第二条 sql 按 id 排序结果 order by 先于 select 执行;
    感觉有些莫名其妙,select 和 order by 的执行顺序究竟是怎么判断的?

    1 条回复    2020-03-24 00:07:18 +08:00
    ASpiral
        1
    ASpiral  
    OP
       2020-03-24 00:07:18 +08:00
    我的提问描述有什么问题吗?怎么都没有大佬回复下…
    select 跟 order by 的执行顺序怎么判断?我用中文搜索不出想要的答案啊…
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1369 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:39 · PVG 01:39 · LAX 10:39 · JFK 13:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.