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
uselessVisitor
V2EX  ›  MySQL

关于 order by 的问题

  •  
  •   uselessVisitor · 2021-02-24 21:42:42 +08:00 · 1009 次点击
    这是一个创建于 1154 天前的主题,其中的信息可能已经有所发展或是发生改变。

    刚刚看了一个帖子关于 order by 的。。自己手撸了一下,发现自己的知识盲区。。

    表结构如下:

    create table test
    (
        count1 int         null,
        count2 int         null,
        name   varchar(16) null,
        type   int         null
    );
    

    sql1:一个聚合函数 使用别名 order by

    select sum(count1) as total1
    from test
    group by type
    order by total1 desc
    

    可以查出结果,是正确的
    sql2:两个聚合函数 使用别名相加 order by

    select sum(count1) as total1,
           sum(count2) as total2
    from test
    group by type
    order by total1 + total2 desc;
    

    报错:[42S22][1247] Reference 'total1' not supported (reference to group function)
    百度了一下,资料比较少,不太懂。。
    sql3:两个聚合函数 不使用别名相加 order by

    select sum(count1) as total1,
           sum(count2) as total2
    from test
    group by type
    order by sum(count1) + sum(count2) desc;
    

    可以查出正确值
    现在我有点搞不懂了,order by 和聚合函数的别名有什么限制吗?
    而且我发现好像只有涉及到 +-等这些操作时,会有问题

    uselessVisitor
        1
    uselessVisitor  
    OP
       2021-02-24 21:47:16 +08:00
    啊。。。我好像懂了。。临时表里面没有 total1+total2 这个字段。。
    zhangysh1995
        2
    zhangysh1995  
       2021-02-26 14:10:12 +08:00
    可以用 MySQL CTE,https://dev.mysql.com/doc/refman/8.0/en/with.html
    性能没研究过,如下:

    with mycte as (
    select sum(count1) as total1,
    sum(count2) as total2
    from test
    group by type
    )

    select * from mycte order by (total1 + total2 ) desc;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3304 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:10 · PVG 22:10 · LAX 07:10 · JFK 10:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.