简体   繁体   English

有没有办法在Vertica中的现有表列上设置AUTO_INCREMENT属性?

[英]Is there a way to set AUTO_INCREMENT property on existing table column in Vertica?

Suppose I have a simple table: 假设我有一个简单的表:

CREATE TABLE user(
  id INT NOT NULL PRIMARY KEY,
  name VARCHAR(32) NOT NULL,
)

Is there a way to alter this table so id will become AUTO_INCREMENT field? 有没有办法改变这个表,所以id将成为AUTO_INCREMENT字段?

I tried the following with no luck: 我试了以下没有运气:

  • ALTER TABLE (no such syntax) ALTER TABLE(没有这样的语法)
  • Creating another table with auto increment ID, and copying the data from the original one (didn't work because of the error: Cannot insert into or update IDENTITY/AUTO_INCREMENT column "id") 创建具有自动增量ID的另一个表,并从原始数据中复制数据(由于错误而无效:无法插入或更新IDENTITY / AUTO_INCREMENT列“id”)

Thanks! 谢谢!

I would try to just rank the rows, and use the sequence for future inserts. 我会尝试对行进行排名,并将序列用于将来的插入。

\set AUTOCOMMIT 'on'

CREATE TABLE t1 (
    val char(1)
);

INSERT INTO t1 VALUES ('a');
INSERT INTO t1 VALUES ('b');
INSERT INTO t1 VALUES ('c');
INSERT INTO t1 VALUES ('d');

CREATE TABLE t2 (
    id int,
    val char(1)
);

INSERT INTO t2 (val, id)
SELECT val, RANK() OVER (ORDER BY val) as id
FROM t1;

SELECT * FROM t2;

We get: 我们得到:

id | val
----+-----
  1 | a
  3 | c
  2 | b
  4 | d

Success! 成功!

Let's prepare the table for future inserts: 让我们为将来的插入准备表格:

-- get the value to start sequence at
SELECT MAX(id) FROM t2;

-- create the sequence
CREATE SEQUENCE seq1 START 5;

-- syntax as of 6.1
-- modify the column to add next value for future rows
ALTER TABLE t2 ALTER COLUMN id SET DEFAULT NEXTVAL('seq1');

Quick test: 快速测试:

INSERT INTO t2 (val) VALUES ('e');
INSERT INTO t2 (val) VALUES ('f');

SELECT * FROM t2;

We get: 我们得到:

id | val
----+-----
  4 | d
  2 | b
  3 | c
  6 | f
  1 | a
  5 | e

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM