实现说明
一个文件里不止一条语句:SELECT / INSERT / CREATE,invitations、customers 都在涉及之列。
逐子句看,这些语句使用了:通过 一个 JOIN 按连接条件合并多张表的行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;把重复值挡在外面的 UNIQUE 约束;补齐缺省列的 DEFAULT 值;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句;把子表行锚到父表上的 REFERENCES 约束。
常见问题
这里涉及哪些关系(表/CTE)?
引用的是 invitations、customers,一个 个 JOIN 把它们连起来。
核心语句
SELECT c.email, i.sent_at
FROM invitations i
JOIN customers c ON c.id = i.customer_id;
CREATE TABLE invitations (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint REFERENCES customers DEFERRABLE INITIALLY DEFERRED,
sent_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE customers (
id bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
email text NOT NULL UNIQUE
);
代码示例
-- 外键声明为 DEFERRABLE INITIALLY DEFERRED:检查推迟到 COMMIT,
-- 数据装载脚本就可以先插子行、再补父行
CREATE TABLE customers (
id bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
email text NOT NULL UNIQUE
);
CREATE TABLE invitations (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint REFERENCES customers DEFERRABLE INITIALLY DEFERRED,
sent_at timestamptz NOT NULL DEFAULT now()
);
BEGIN;
-- 子行先插入:FK 校验被推迟,父行随后补上
INSERT INTO invitations (customer_id) VALUES (42);
INSERT INTO customers (id, email) VALUES (42, '[email protected]');
COMMIT;
-- 校验通过后再查一次关联,确认父子行都落库
SELECT c.email, i.sent_at
FROM invitations i
JOIN customers c ON c.id = i.customer_id;
-- 若父行最终缺失,COMMIT 时才报错:
-- ERROR: insert or update on table "invitations" violates foreign key constraint