V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ASpiral
V2EX  ›  问与答

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

  •  
  •   ASpiral · Mar 23, 2020 · 1292 views
    This topic created in 2227 days ago, the information mentioned may be changed or developed.

    一直以为 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 replies    2020-03-24 00:07:18 +08:00
    ASpiral
        1
    ASpiral  
    OP
       Mar 24, 2020
    我的提问描述有什么问题吗?怎么都没有大佬回复下…
    select 跟 order by 的执行顺序怎么判断?我用中文搜索不出想要的答案啊…
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1004 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 19:19 · PVG 03:19 · LAX 12:19 · JFK 15:19
    ♥ Do have faith in what you're doing.