PostgreSQL 9.4表中的唯一ID

时间:2016-04-30 12:00:32

标签: sql postgresql postgresql-9.3

我想在PostgreSQL 9.4表中插入唯一的ID记录。

INSERT INTO ACCOUNT_HISTORY(ID, ACCOUNT_ID, USERNAME, COMMENT, CREATED) VALUES (?, (select ID from ACCOUNT where USER_NAME = ?), ?, ?, CURRENT_DATE)

表格

CREATE TABLE ACCOUNT_HISTORY(
 ID INTEGER NOT NULL,
 ACCOUNT_ID INTEGER,
 USERNAME TEXT,
 COMMENT TEXT,
 CREATED DATE
)
;

CREATE INDEX IX_RELATIONSHIP8 ON ACCOUNT_HISTORY (ACCOUNT_ID)
;

如何为每个插入查询生成唯一ID?

1 个答案:

答案 0 :(得分:2)

使用serial

CREATE TABLE ACCOUNT_HISTORY (
   ID SERIAL,
   ACCOUNT_ID INTEGER,
   USERNAME TEXT,
   COMMENT TEXT,
   CREATED DATE
);

然后,不要将其包含在insert语句中:

INSERT INTO ACCOUNT_HISTORY(ACCOUNT_ID, USERNAME, COMMENT, CREATED)
    SELECT ID, ?, ?, ?, CURRENT_DATE
    FROM ACCOUNT 
    WHERE USER_NAME = ?;

编辑:

如果表格中有数据(所以你不想放弃它):

create temporary table temp_account_history as
    select *
    from account_history;

drop account_history;

CREATE TABLE ACCOUNT_HISTORY (
   ID SERIAL,
   ACCOUNT_ID INTEGER,
   USERNAME TEXT,
   COMMENT TEXT,
   CREATED NOT NULL DEFAULT CURRENT_DATE
);

INSERT INTO ACCOUNT_HISTORY(ACCOUNT_ID, USERNAME, COMMENT, CREATED)
    SELECT ACCOUNT_ID, USERNAME, COMMENT, CREATED
    FROM TEMP_ACCOUNT_HISTORY;

请注意,这也为CREATED提供了默认值,因此您不必在后续插入中包含该值。