为什么Postgresql不允许INSERT SELECT查询中的分组集?

时间:2017-09-14 22:22:35

标签: sql postgresql

这里的问题很简单,因为Postgresql不允许以下查询结构:

-- TABLE OF FACTS
CREATE TABLE facts_table (
    id integer NOT NULL,
    description CHARACTER VARYING(50),
    amount NUMERIC(12,2) DEFAULT 0,
    quantity INTEGER,
    detail_1 CHARACTER VARYING(50),
    detail_2 CHARACTER VARYING(50),
    detail_3 CHARACTER VARYING(50),
    time TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT LOCALTIMESTAMP(0)
);
ALTER TABLE facts_table ADD PRIMARY KEY(id);

-- SUMMARIZED TABLE
CREATE TABLE table_cube (
    id INTEGER,
    description CHARACTER VARYING(50),
    amount NUMERIC(12,2) DEFAULT 0,
    quantity INTEGER,
    time TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT LOCALTIMESTAMP(0)
);
ALTER TABLE table_cube ADD PRIMARY KEY(id);

INSERT INTO table_cube(id, description, amount, quantity, time)
    SELECT
        id,
        description,
        SUM(amount) AS amount,
        SUM(quantity) AS quantity,
        time
    FROM facts_table
    GROUP BY CUBE(id, description, time);
----------------------------------------------------------------
ERROR: grouping sets are not allowed in INSERT SELECT queries.

我认为很明显CUBE会在每个指定为分组集的字段上产生null结果(因为它会计算每个可能的组合),因此我无法在{{1}中插入该行表格,那么,Postgres只是假设,我试图在带有PK字段的表中插入一行?即使table_cube表没有PK,也无法实现。

感谢。

版本:PostgreSQL 9.6

1 个答案:

答案 0 :(得分:1)

  

您已将table_cube(id)定义为主键。所以,如果Cube包含null   值,它不能插入。我已经检查过没有id作为Primary   键,它工作正常,当将id定义为主键时,我收到错误:

"ERROR:id contains null values"  SQL state: 23502   
  

正如Haleemur Ali所说,

  "If a constraint is required, use a unique index with all the grouping 
  set columns: CREATE UNIQUE INDEX unq_table_cube_id_description_time ON 
  table_cube(id, description, time); Please update your question with more 
  information on database & version."
  

是个不错的选择。但是您必须删除“Id”上的主键并仅按上面的建议分配唯一键,因为主键和唯一键再次出现此错误:

   ERROR:  null value in column "id" violates not-null constraint
   DETAIL:  Failing row contains (null, null, 1300, 1522, null).
   SQL state: 23502
  

因此,结论是,使用唯一索引不需要主键或使用多维数据集,不需要唯一索引或主键。