zoukankan      html  css  js  c++  java
  • PostgreSQL对GROUP BY子句使用常量的特殊限制

    一、问题描述

    最近,一个统计程序从Oracle移植到PostgreSQL(版本9.4)时,接连报告错误:

    错误信息1: postgresql group by position 0 is not in select list.

    错误信息2: non-integer constant in GROUP BY.

    产生错误的sql类似于:

    insert into sum_tab (IntField1, IntField2, StrField1, StrField2, cnt)
    select IntField, 0, StrField, 'null', count(*) from detail_tab
    where ...
    group by IntField, 0, StrField, 'null';

    其中,detail_tab表保存原始的详细记录,而sum_tab保存统计后的记录信息。

    二、原因分析

    经过测试,发现错误是因为PostgreSQL对GROUP BY子句使对使用常量有着特殊限制。测试过程过于繁琐,这里不再一一写demo了,直接给出结论:

    1 GROUP BY子句中不能使用字符串型、浮点数型常量, 否则会报告错误信息2。如:

    select IntField, 'aaa', count(*) from tab group by IntField, 'aaa'; 
    select IntField, 0.5, count(*) from tab group by IntField, 0.5;

    2 GROUP BY子句中也不能使用0和负整数,否则会报错误信息1。如:

    select IntField, 0, count(*) from tab group by IntField, 0;
    select IntField, -1, count(*) from tab group by IntField, -1;

    那么,GROUP BY子句中可以使用什么类型的常量?经测试,在常用的类型中,正整数、日期型常量均可以。

    select IntField, 1, count(*) from tab group by IntField, 1;
    select IntField, now(), count(*) from tab group by IntField, now();

    对于第一节中的sql,因为0和‘null’有着特殊的含义,该如何处理?

    实际上,在GROUP BY子句中可以不使用任何常量,只列出聚集字段即可,即将第一节中的sql改为:

    insert into sum_tab (IntField1, IntField2, StrField1, StrField2, cnt)
    select IntField, 0, StrField, 'null', count(*) from detail_tab
    where ...
    group by IntField, StrField;

    三、MySQL的情况

    考虑到将来统计程序也可能移植到MySQL(版本8.x),随后进行了类似测试,结论为:

    1 支持不带任何常量的GROUP BY子句;

    2 支持带非0整数、浮点数(包括0.0)、字符串、日期型常量的GROUP BY子句。

    也就是说,在常见类型中,MySQL 8的GROUP BY子句支持除整数0(非浮点数0.0)以外的所有类型。否则,会报错:

    ERROR 1054 (42S22): Unknown column '0' in 'group statement'

    顺便说一句,Oracle对整数0也支持。

     四、结论

    1. PostgreSQL的GROUP BY子句只支持正整数、日期型的常量;
    2. MySQL支持除非0整数以外的所有常规类型常量,而Oracle似乎全部支持;
    3. 如果有在各各数据库平台可移植的需求,尽量不要在GROUP BY子句中使用常量。
  • 相关阅读:
    LeetCode:Remove Duplicates from Sorted List
    LeetCode:Remove Nth Node From End of List
    LeetCode:Delete Node in a Linked List
    LeetCode:Rotate Image
    LeetCode:Anagrams(字母颠倒)
    LeetCode:Single NumberⅡ
    LeetCode:Single Number
    LeetCode:Longest Common Prefix
    bzoj1025
    bzoj1024
  • 原文地址:https://www.cnblogs.com/wggj/p/12653136.html
Copyright © 2011-2022 走看看