暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Mysql 和 SUNDB 关于查询语句的 GROUP BY 子句中列别名的使用差异

原创 科蓝SUNDB编辑部 2022-11-04
404

1. 问题描述

Mysql 应用迁移到SUNDB 数据库后一下查询语句报错:
样例代码:
建表:

create table a11y_synthesis_log(
channel_id integer,
create_time date,
chars_count integer,
utf8_bytes_count integer,
gbk_bytes_count integer);

sql:

SELECT
channel_id,
TO_CHAR(create_time,‘YYYY-MM’) AS which_month,
sum(chars_count) AS chars,
sum(utf8_bytes_count) AS utf8_bytes,
sum(gbk_bytes_count) AS gbk_bytes
FROM a11y_synthesis_log
GROUP BY channel_id,which_month
ORDER BY which_month;

image.png

2. 问题原因

sql语句的group by 子句包含 which_month 列别名, mysql 对查询进行了增强可以在 group by 子句中使用列别名。
但SUNDB数据库的 group by 子句中不能使用列别名,在 order by 子句中可以使用列别名。
之所以出现此种情况和sql语句各部分执行顺序相关在执行group by 时还未执行 select 部分所以别名未生效,而执行order by 的时候select 中的别名已经生效所以可以使用。

3. 解决方案

将sql 进行如下等价改写(group by 中的 which_month 替换为TO_CHAR(create_time,‘YYYY-MM’));
SELECT
channel_id,
TO_CHAR(create_time,‘YYYY-MM’) AS which_month,
sum(chars_count) AS chars,
sum(utf8_bytes_count) AS utf8_bytes,
sum(gbk_bytes_count) AS gbk_bytes
FROM a11y_synthesis_log
GROUP BY channel_id,TO_CHAR(create_time,‘YYYY-MM’)
ORDER BY which_month;
image.png

最后修改时间:2023-07-17 14:50:03
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论