功能说明
示例先用一条语句插入四行商品数据,并在主键冲突时执行更新,从而实现插入或更新的原子操作。冲突分支会把商品名和单价替换为新值,库存则在原有数量上累加。第二段用 INSERT INTO … SELECT 从 order_items 汇总每个订单的商品数与金额写入 order_summary,遇到已存在的 order_id 时跳过。
关键代码
INSERT INTO products (…) VALUES (…), (…), (…) 一次写入多行。ON CONFLICT (product_id) 指定冲突目标,DO UPDATE SET 中使用 EXCLUDED.product_name 等引用本次准备插入的值;DO UPDATE 后面的 WHERE 让更新只在价格变化或库存不足时发生,避免无意义的写入。插入汇总表时使用 ON CONFLICT (order_id) DO NOTHING,冲突行直接忽略。
使用注意
ON CONFLICT 的冲突目标必须有唯一约束或唯一索引支撑,否则语句无法确定冲突条件。EXCLUDED 代表待插入行而不是表中已有行,更新已有表字段时要显式写出表名或别名。多行插入与 upsert 都在单条语句内完成,具备原子性,但仍需注意批量大小对锁与日志的影响。DO NOTHING 会静默跳过冲突,调用方应确认这符合业务预期。
验证方式
在测试库执行第一段语句两次:首次应插入四行,第二次应按 WHERE 条件只更新价格或库存变化的行,并核对库存为累加结果。再向 order_items 插入数据后执行第二段语句,确认 order_summary 生成汇总行,重复执行不会产生重复记录。
代码示例
INSERT INTO products (product_id, product_name, unit_price, stock_quantity, category_id)
VALUES
(101, 'Wireless Mouse', 29.99, 150, 1),
(102, 'USB Keyboard', 49.99, 80, 1),
(103, 'HD Monitor', 299.99, 25, 1),
(104, 'Webcam', 89.99, 60, 1)
ON CONFLICT (product_id)
DO UPDATE SET
product_name = EXCLUDED.product_name,
unit_price = EXCLUDED.unit_price,
stock_quantity = products.stock_quantity + EXCLUDED.stock_quantity
WHERE products.unit_price != EXCLUDED.unit_price
OR products.stock_quantity < EXCLUDED.stock_quantity;
-- Insert from a SELECT query
INSERT INTO order_summary (order_id, total_items, total_amount)
SELECT
order_id,
SUM(quantity) AS total_items,
SUM(quantity * unit_price) AS total_amount
FROM order_items
GROUP BY order_id
ON CONFLICT (order_id) DO NOTHING;