插入数据并强制引用完整性
在此步骤中,你将把数据插入到 customers
和 orders
表中,确保引用完整性(referential integrity)得到维护。这意味着你不能为一个不存在于 customers
表中的客户添加订单。
理解引用完整性
引用完整性确保表之间的关系保持一致。在我们的例子中,这意味着 orders
表中的 customer_id
必须存在于 customers
表中。
步骤 1:将数据插入到 customers
表中
使用以下 SQL 命令在 psql
shell 中将数据插入到 customers
表中:
INSERT INTO customers (first_name, last_name, email) VALUES
('John', 'Doe', '[email protected] '),
('Jane', 'Smith', '[email protected] '),
('David', 'Lee', '[email protected] ');
此命令将三个客户添加到 customers
表中。customer_id
会自动生成。
步骤 2:验证数据是否插入到 customers
表中
通过查询 customers
表来验证数据是否已正确插入:
SELECT * FROM customers;
你应该看到你刚刚插入的三个客户,以及他们自动生成的 customer_id
值。输出应类似于这样:
customer_id | first_name | last_name | email
-------------+------------+-----------+------------------------
1 | John | Doe | [email protected]
2 | Jane | Smith | [email protected]
3 | David | Lee | [email protected]
(3 rows)
步骤 3:将数据插入到 orders
表中
将数据插入到 orders
表中,引用 customers
表中的 customer_id
值:
INSERT INTO orders (customer_id, order_date, total_amount) VALUES
(1, '2023-11-01', 100.00),
(2, '2023-11-05', 250.50),
(1, '2023-11-10', 75.25),
(3, '2023-11-15', 120.00);
此命令将四个订单添加到 orders
表中。每个订单都与 customers
表中的 customer_id
相关联。
步骤 4:验证数据是否插入到 orders
表中
通过查询 orders
表来验证数据是否已正确插入:
SELECT * FROM orders;
你应该看到你刚刚插入的四个订单。输出应类似于这样:
order_id | customer_id | order_date | total_amount
----------+-------------+------------+--------------
1 | 1 | 2023-11-01 | 100.00
2 | 2 | 2023-11-05 | 250.50
3 | 1 | 2023-11-10 | 75.25
4 | 3 | 2023-11-15 | 120.00
(4 rows)
步骤 5:尝试插入无效数据(演示引用完整性)
为了演示引用完整性约束,请尝试插入一个 customer_id
在 customers
表中不存在的订单:
INSERT INTO orders (customer_id, order_date, total_amount) VALUES
(4, '2023-11-20', 50.00);
你应该看到类似于这样的错误消息:
ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(4) is not present in table "customers".
此错误消息确认外键约束正在工作。数据库阻止插入订单,因为 customer_id
4 在 customers
表中不存在。
你现在已经成功地将数据插入到 customers
和 orders
表中,确保了引用完整性。