扫码一下
查看教程更方便
postgresql 使用 create table 语句在数据库中创建表。
create table 语法格式如下:
create table table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnn datatype,
primary key( 一个或多个列 )
);
create table 是一个关键词,用于告诉数据库系统将创建一个数据表。
表名字必需在同一模式中的其它表、 序列、索引、视图或外部表名字中唯一。
create table 在当前数据库创建一个新的空白表,该表将由发出此命令的用户所拥有。
表格中的每个字段都会定义数据类型,如下:
以下创建了一个表,表名为 company 表格,主键为 id,not null 表示字段不允许包含 null 值:
create table company(
id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real
);
接下来我们再创建一个表,在后面章节会用到:
create table department(
id int primary key not null,
dept char(50) not null,
emp_id int not null
);
我们可以使用 \d 命令来查看表格是否创建成功:
jiyk_db=# \d
list of relations
schema | name | type | owner
-------- ------------ ------- ----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
\d tablename 查看表格信息:
jiyik_db=# \d company
table "public.company"
column | type | collation | nullable | default
--------- --------------- ----------- ---------- ---------
id | integer | | not null |
name | text | | not null |
age | integer | | not null |
address | character(50) | | |
salary | real | | |
indexes:
"company_pkey" primary key, btree (id)