E-commerce 顺序系统
你将构建什么
完整 e-commerce Schema 使用 four 表: customers, products, 顺序, and order_items (junction 表使用 extra 数据如 数量 and price).
学习目标
- 设计许多-到-许多关系使用 junction 表
- Use foreign 键到 enforce referential integrity
- 存储 historical prices in order_items (price at 时间的 顺序)
- 编写查询到 retrieve 完整顺序 details
前置要求
- Foreign 键 and 关系
- JOIN 查询
- 理解的 one-到-许多 and 许多-到-许多
步骤
- 1
创建 customers and products
创建 customers and products 表使用基础字段.
代码CREATE TABLE customers ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL ); CREATE TABLE products ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, price NUMERIC(10,2) NOT NULL CHECK (price > 0) );预期结果
Customers and products 表是 创建.
- 2
创建顺序 and order_items
创建顺序表 (请求头) and order_items 表 (行项). order_items 是 junction 表那个也 存储 price at 时间的 purchase.
代码CREATE TABLE orders ( id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(id), order_date TIMESTAMP DEFAULT NOW() ); CREATE TABLE order_items ( id SERIAL PRIMARY KEY, order_id INTEGER REFERENCES orders(id), product_id INTEGER REFERENCES products(id), quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price NUMERIC(10,2) NOT NULL -- price at time of order );预期结果
顺序 and order_items 表是 创建使用 proper foreign 键.
- 3
Insert 顺序使用项
Insert customer, two products, 顺序, and two 顺序项. 存储 current product price in unit_price.
代码INSERT INTO customers (name, email) VALUES ('Ada', '[email protected]'); INSERT INTO products (name, price) VALUES ('Widget', 9.99), ('Gadget', 19.99); INSERT INTO orders (customer_id) VALUES (1); INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (1, 1, 3, 9.99), -- 3 Widgets at $9.99 (1, 2, 1, 19.99); -- 1 Gadget at $19.99预期结果
完整顺序使用 two 行项 是创建.
- 4
查询完整顺序
编写查询那个连接所有 four 表到 show 完整顺序: customer name, 顺序 date, product names, 数量, and 行总计.
代码SELECT c.name AS customer, o.order_date, p.name AS product, oi.quantity, oi.unit_price, (oi.quantity * oi.unit_price) AS line_total FROM orders o INNER JOIN customers c ON o.customer_id = c.id INNER JOIN order_items oi ON oi.order_id = o.id INNER JOIN products p ON oi.product_id = p.id WHERE o.id = 1;预期结果
完整顺序 report 使用 customer, products, 数量, and 总计.
- 5
添加索引优化查询
为频繁查询的列创建索引,提升查询性能。索引是数据库性能优化的首要手段,但需注意写操作的开销。
代码-- Create indexes on frequently filtered columns CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_orders_user_id ON orders(user_id); CREATE INDEX idx_orders_created_at ON orders(created_at DESC); -- Verify the index is used EXPLAIN SELECT * FROM orders WHERE user_id = 42;预期结果
EXPLAIN 输出显示使用 idx_orders_user_id 索引扫描而非全表扫描。
自己动手试试
你学到了什么
你设计真实 e-commerce Schema 使用许多-到-许多关系通过 junction 表, 存储 historical 数据 (prices at 顺序时间), and wrote four-表连接查询.
相关资源
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。