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;

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;





