【问题标题】:SERIAL fields / Auto incrementSERIAL 字段/自动递增
【发布时间】:2021-06-07 12:15:59
【问题描述】:

任务表明:

使用以下字段创建一个名为 automagic 的表:

id 字段是一个自动递增的序列字段。 名称字段,最多允许 32 个字符,但不能超过 此字段是必需的。 高度字段是必需的浮点数。 我的代码是:

CREATE TABLE automatic (
    id SERIAL PRIMARY KEY NOT NULL, 
    name CHAR (32), 
    height numeric);

但是,自我评估者回答了这个期望没有高度的 INSERT 失败,它没有失败。

之后,我尝试了这个

CREATE TABLE automatic (
    id int not null auto_increment primary key, 
    name varchar(32) not null, 
    height float not null);

得到了

错误:“auto_increment”处或附近的语法错误
LINE 1: CREATE TABLE automagic (id int not null auto_increment prima...\

SQL 状态:42601
字符:41

【问题讨论】:

  • Postgres 不支持auto_increment。所以,在create table 中是不合适的。您似乎知道答案(至少一个答案),因为它在问题的标题中。
  • 你在哪里找到in the manual 的语法?
  • 它现在工作了 CREATE TABLE automagic (id SERIAL PRIMARY KEY NOT NULL, name varchar(32), height float not null);

标签: sql postgresql


【解决方案1】:

你可以试试这样的:

CREATE TABLE automagic (
  id int NOT NULL,
  name varchar(32) NOT NULL,
  height float NOT NULL
);

CREATE SEQUENCE automagic_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER SEQUENCE automagic_id_seq OWNED BY automagic.id;

ALTER TABLE ONLY automagic ALTER COLUMN id SET DEFAULT nextval('automagic_id_seq'::regclass);

编辑:

正如@a_horse_with_no_name 所指出的,这样更好:

CREATE TABLE automagic (
  id int GENERATED ALWAYS AS IDENTITY,
  name varchar(32) NOT NULL,
  height float NOT NULL
);

【讨论】:

  • @a_horse_with_no_name:我已经编辑了我的答案,但请随意写下你自己的答案,我会删除我的。
【解决方案2】:

也许试试这个:

CREATE TABLE automagic (
id SERIAL,
name VARCHAR(32) NOT NULL,
height FLOAT NOT NULL)

【讨论】:

  • 为什么你更喜欢这个而不是之前发布的答案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2015-11-03
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多