本节使用的表
customers
postgres=# \d customers
Table "public.customers"
Column | Type | Collation | Nullable | Default
--------------+----------------+-----------+----------+---------
cust_id | character(10) | | not null |
cust_name | character(50) | | not null |
cust_address | character(50) | | |
cust_city | character(50) | | |
cust_state | character(5) | | |
cust_zip | character(10) | | |
cust_country | character(50) | | |
cust_contact | character(50) | | |
cust_email | character(255) | | |
Indexes:
"customers_pkey" PRIMARY KEY, btree (cust_id)
Referenced by:
TABLE "orders" CONSTRAINT "fk_orders_customers" FOREIGN KEY (cust_id) REFERENCES customers(cust_id)
SELECT
*
FROM
customers;
cust_id | cust_name | cust_address | cust_city | cust_state | cust_zip | cust_country | cust_contact
| cust_email
------------+---------------+----------------------+-----------+------------+----------+--------------+--------------------
---+----------------------------
1000000001 | Village Toys | 200 Maple Lane | Detroit | MI | 44444 | USA | John Smith
| sales@villagetoys.com
1000000002 | Kids Place | 333 South Lake Drive | Columbus | OH | 43333 | USA | Michelle Green
|
1000000003 | Fun4All | 1 Sunny Place | Muncie | IN | 42222 | USA | Jim Jones
| jjones@fun4all.com
1000000004 | Fun4All | 829 Riverside Drive | Phoenix | AZ | 88888 | USA | Denise L. Stephens
| dstephens@fun4all.com
1000000005 | The Toy Store | 4545 53rd Street | Chicago | IL | 54545 | USA | Kim Howard
|
(5 rows)
更新数据
有两种使用UPDATE
的方式:
- 更新表中的特定行;
- 更新表中的所有行。
UPDATE
customers
SET
cust_email = NULL
WHERE
cust_id = '1000000005';
其中NULL用来去除cust_email列中的值。这与保存空字符串不同(用‘’表示,是一个值),NULL表示没有值。
删除数据
有两种使用DELETE
的方式:
- 从表中删除特定的行;
- 从表中删除所有行。
DELETE FROM
customers
WHERE
cust_id = '1000000007';
如果省略WHERE
子句,它将删除表中所有行,但是,DELETE
不删除表本身。如果想从表中删除所有行,不要使用DELETE
。可使用TRUNCATE TABLE
语句,它完成相同的工作,而速度更快(因为不记录数据的变动)。
前面介绍过联结,简单联结两个表只需要这两个表中的公用字段,也可以让DBMS通过使用外键来严格实施关系。存在外键时,DBMS使用它们实施引用完整性。例如要向products表中插入一个新产品,DBMS不允许通过未知的vend_id插入它,因为vend_id列是作为外键连接到vendors表的。
使用外键确保引用完整性的一个好处是:DBMS通常可以防止删除某个关系需要用到的行。例如,要从products表中删除一个产品,而这个产品用在orderitems的已有订单中,那么DELETE
语句将抛出错误并中止。这是总要定义外键的另一个理由。