创建一个PostgreSQL序列的字段(这不是记录的ID) [英] Creating a PostgreSQL sequence to a field (which is not the ID of the record)

查看:272
本文介绍了创建一个PostgreSQL序列的字段(这不是记录的ID)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Ruby on Rails应用程序。我们使用的是PostgreSQL数据库。

I am working on a Ruby on Rails app. We are using a PostgreSQL database.

有一个表名为分数以下列:

Column        | Type
--------------+-----------------------
id            | integer
value         | double precision
ran_at        | timestamp
active        | boolean
build_id      | bigint
metric_id     | integer
platform_id   | integer
mode_id       | integer
machine_id    | integer
higher_better | boolean
job_id        | integer
variation_id  | integer
step          | character varying(255)

我需要添加的作业ID (注意:没有型号为工作)。

I need to add a sequence to job_id (note: there is no model for job).

如何创建这个序列?

推荐答案

使用的 CREATE SEQUENCE

CREATE SEQUENCE job_seq;

接着一列默认添加到 scores.job_id

ALTER TABLE scores ALTER COLUMN job_id SET DEFAULT nextval('job_seq');

如果你想的绑定的顺序为列,也跑:

If you want to bind the sequence to the column, also run:

ALTER SEQUENCE job_seq OWNED BY scores.job_id;

所有这一切都可以使用伪数据类型的 系列 该列作业ID 来开始:

  • <一个href="http://stackoverflow.com/questions/14649682/safely-and-cleanly-rename-tables-that-use-serial-primary-key-columns-in-postgres/14651788#14651788">Safely和干净重命名使用串行主键列在Postgres的表?

剩下的唯一的区别,一个系列列也被设置为 NOT NULL 。您可能会或可能不希望出现这种情况,太:

The only remaining difference, a serial column is also set to NOT NULL. You may or may not want that, too:

ALTER TABLE scores ALTER COLUMN job_id SET NOT NULL;

但是您的不能的只是改变现有的整数的类型:

But you cannot just alter the type of an existing integer:

ALTER TABLE scores ALTER job_id TYPE serial;

系列不是实际的数据类型。这只是一个符号上的便利功能 CREATE TABLE

serial is not an actual data type. It's just a notational convenience feature for CREATE TABLE.

这篇关于创建一个PostgreSQL序列的字段(这不是记录的ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆