Skip to Content
PostgreSQL:快速入门,第3版
book

PostgreSQL:快速入门,第3版

by Regina O. Obe, Leo S. Hsu
May 2025
Intermediate to advanced
314 pages
4h 10m
Chinese
O'Reilly Media, Inc.
Content preview from PostgreSQL:快速入门,第3版

第 6 章 表、约束和索引 表、约束和索引

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

表是关系数据库存储的构建 块。构造表,使它们形成有意义的关系,是关系数据库设计的关键。在 PostgreSQL 中,约束强化了表之间的关系。为了将表与一堆数据区分开来,我们建立了索引。,索引指向表中的位置,这样你就不必每次都从上到下搜索表中的内容。

在本章中,我们将介绍创建表格和添加行的语法。然后,我们将介绍约束,以确保数据不会出错。最后,我们将向你展示如何为表添加索引,以加快搜索速度。

为表编制索引既是一项编程任务,也是一项实验工作。索引的滥用比无用更糟糕。并非所有索引都是一样的。算法专家为不同的数据类型和查询类型设计了不同种类的索引,所有这些都是为了从查询中获得最后一点速度。

表格

除了普通数据表,PostgreSQL 还提供了几种比较少见的表:临时表、无记录表、继承表、类型表和外来表(将在第 10 章中介绍)。

基本表格创建

例 6-1显示了表创建语法,它与所有 SQL 数据库中的创建语法相似。

例 6-1. 创建基本表格
CREATE TABLE logs (
log_id serial PRIMARY KEY, 1
user_name varchar(50), 2
description text, 3
log_ts timestamp with time zone NOT NULL DEFAULT current_timestamp
); 4
CREATE INDEX idx_logs_log_ts ON logs USING btree (log_ts);
1

serial 是数据类型 ,用于表示递增的自动编号。添加序列列会自动在数据库模式中添加相应的序列对象。序列数据类型总是整数,默认值设置为序列对象的下一个值。每个表通常只有一个序列列,通常用作主键。对于非常大的表,应选择相关的 。 bigserial

2

varchar 是 的缩写,表示 "字符变化",是一种长度可变的字符串,类似于其他数据库中的字符串。您不需要指定最大长度;如果不指定, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Docker:入门与实践,第三版

Docker:入门与实践,第三版

Sean P. Kane, Karl Matthias
AI工程

AI工程

Chip Huyen

Publisher Resources

ISBN: 9798341658431