有没有办法在不删除表的情况下将现有主键类型从int改为serial?我已经有很多数据在表中,我不想删除它.

推荐答案

将整数转换为串行more or less only means adding a sequence default to the value,使其成为串行;

  • Pick a starting value for the serial, greater than any existing value in the table
    SELECT MAX(id)+1 FROM mytable

  • Create a sequence for the serial (tablename_columnname_seq is a good name)
    CREATE SEQUENCE test_id_seq MINVALUE 3 (assuming you want to start at 3)

  • Alter the default of the column to use the sequence
    ALTER TABLE test ALTER id SET DEFAULT nextval('test_id_seq')

  • Alter the sequence to be owned by the table/column;
    ALTER SEQUENCE test_id_seq OWNED BY test.id

A very simple SQLfiddle demo

和往常一样,养成一个习惯,运行一个完整的备份,运行来自互联网上随机人群的SQL查询;-)

Postgresql相关问答推荐

在PL/pgSQL中使用循环时缓存

如何使用postgr sql regex删除重复项和inc表记录

在输入稍有错误的PostgreSQL表中进行快速字符串搜索

如何获取实例化视图的列级权限?

无法在PostgreSQL中创建方案和表

ANTLR4 PostgreSQL语法被 destruct 了吗?

SQLX::Query!带有UUID::UUID的宏在Rust中编译失败

我可以使用 SQLAlchemy 映射数据类创建 Postgres `GENERATED ALWAYS AS` 列吗?

使用FastAPI和PostgreSQL进行测试

无法从外部连接到在 AWS EC2 实例上运行的 Postgres

在 postgresql 数据库 timestampz 中保留用户偏移量

如何在typeorm和嵌套js中将运行时变量设置为postgresql

Windows上的psql:错误:编码UTF8的字节序列无效:0xc8 0x20

从 Postgres 字段中的多个值中进行 Select

try 访问本地主机中的数据库时如何解决Error: The server does not support SSL connections?

Postgres 日期重叠约束

PGError:错误: column of relation does not exist

带有 WITH 子句的查询时出现 Postgresmissing FROM-clause entry错误

PostgreSQL 使用 UUID 与文本作为主键

postgres LISTEN/NOTIFY rails