关于 order by 的问题

2021-02-24 21:42:42 +08:00
 uselessVisitor

刚刚看了一个帖子关于 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 和聚合函数的别名有什么限制吗?
而且我发现好像只有涉及到 +-等这些操作时,会有问题

1017 次点击
所在节点    MySQL
2 条回复
uselessVisitor
2021-02-24 21:47:16 +08:00
啊。。。我好像懂了。。临时表里面没有 total1+total2 这个字段。。
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;

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/755983

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX