PostgreSQL:INSERT INTO 语法错误

DjH*_*DjH 1 sql postgresql sql-insert

我正在学习 Postgres 的旧教程,因此自发布以来可能发生了一些变化。在本教程(使用 psql)中,我创建一个表,然后执行一些insert语句。psql以下是导致错误的教程和相应命令:

http://www.postgresqlforbeginners.com/2010/11/create-table-and-constraints.html

create table people(
   id int PRIMARY KEY,
   name varchar NOT NULL
);
insert into people(0,'Steve Jobs');
insert into people(1,'Mike Markkula');
insert into people(2,'Mike Scott');
insert into people(3,'John Sculley');
insert into people(4,'Michael Spindler');
insert into people(5,'Gil Amelio');
insert into people(6,'Mike Scott');
Run Code Online (Sandbox Code Playgroud)

对于每个插入语句,我都会收到此错误:

ERROR:  syntax error at or near "0"
LINE 1: insert into people(0,'Steve Jobs');
                           ^
Run Code Online (Sandbox Code Playgroud)

我尝试过复制粘贴、大写 sql 命令(即INSERT)、从 shell 外部运行命令psql、添加空格、使用"而不是'引号...所有结果都会导致相同的错误。有什么变化或者我可能做错了什么吗?

Gor*_*off 6

问题是缺少values(如评论中所述)。

我想提出一些建议。首先,每当您使用 时insert,您应该始终列出列。如果您正在学习语言,这一点尤其重要——您应该学习良好的习惯。

其次,你不需要多个inserts. 插入多行的更短方法是:

insert into people (id, name)
    values (0,'Steve Jobs'),
           (1,'Mike Markkula'),
           (2,'Mike Scott'),
           (3,'John Sculley'),
           (4,'Michael Spindler'),
           (5,'Gil Amelio'),
           (6,'Mike Scott');
Run Code Online (Sandbox Code Playgroud)

你应该了解serial. 编写此代码的更常见方法是:

create table people (
   id serial PRIMARY KEY,
   name varchar NOT NULL
);

insert into people (name)
    values ('Steve Jobs'),
           ('Mike Markkula'),
           ('Mike Scott'),
           ('John Sculley'),
           ('Michael Spindler'),
           ('Gil Amelio'),
           ('Mike Scott');
Run Code Online (Sandbox Code Playgroud)

id由数据库自动分配(从而不是1开始0)。

我应该补充一点:我个人对varchar没有长度感到不舒服。这在 Postgres 中完全没问题,但有些数据库会将其解释为varchar(1).