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

order by 失效问题

  •  
  •   Leo818 · 2021-02-24 15:27:35 +08:00 · 1830 次点击
    这是一个创建于 1128 天前的主题,其中的信息可能已经有所发展或是发生改变。
    SELECT
    SUM( IFNULL( r.read_total, 0 ) ) AS ReadCount,
    SUM( IFNULL( r.get_total, 0 ) ) AS GetCount
    FROM
    report_promote_detail AS r
    LEFT JOIN pl_promote AS p ON r.promote_id = p.id
    WHERE
    r.planet_id = 45
    AND r.date
    GROUP BY
    r.promote_id
    ORDER BY
    ReadCount + GetCount DESC


    以上代码,使用两个数的和进行排序结果不对

    目前可以有两种方式解决这个问题
    1 、
    ReadCount + GetCount 换成 SUM( IFNULL( r.read_total, 0 ) ) +SUM( IFNULL( r.get_total, 0 ) )
    排序结果是正确的
    2 、
    SELECT 中 SUM( IFNULL( r.read_total, 0 ) ) +SUM( IFNULL( r.get_total, 0 ) ) AS Total ...... ORDER BY Total DESC
    这个结果也没问题

    请教下这个是什么情况,为啥两个别名相加不行呢?(之前也这样做过,但是可以,猜测是因为 SUM 函数或者 GROUP BY ?)
    6 条回复    2021-02-25 10:55:44 +08:00
    uselessVisitor
        1
    uselessVisitor  
       2021-02-24 20:41:58 +08:00
    加个括号试试?
    uselessVisitor
        2
    uselessVisitor  
       2021-02-24 21:11:19 +08:00
    select sum(count2) as c1,
    sum(count1) as c2
    from test
    group by type
    order by c1 + c2 desc
    (报错)[42S22][1247] Reference 'c1' not supported (reference to group function)
    uselessVisitor
        3
    uselessVisitor  
       2021-02-24 21:14:22 +08:00
    应该和 聚合函数 有关。。好像聚合函数别名不能 order by 。。
    Leo818
        4
    Leo818  
    OP
       2021-02-25 09:12:15 +08:00
    @beichenhpy 谢谢你的回复,请问下是怎么得到的这个错误提示呢,我用 Navicat 执行是正常的没有报错,要是有报错提示,可能我就没那么纠结这个问题了
    uselessVisitor
        5
    uselessVisitor  
       2021-02-25 09:23:40 +08:00
    @Leo818 我用 datagrip 写的。。不懂为啥你不报错。。同事用 oracle 都不允许 order by 使用别名。。
    Leo818
        6
    Leo818  
    OP
       2021-02-25 10:55:44 +08:00
    @beichenhpy 我朋友试了下,在他们那里也报错,他们用的是 mysql 5.X,我的是 mysql 8.x 就不报错,莫非是我版本问题,又或者我用的是假的?哈哈哈哈,太坑了,要是早就报错,我也不至于那么纠结
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1521 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:17 · PVG 01:17 · LAX 10:17 · JFK 13:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.