实现说明
实际执行的是 INSERT / CREATE / ALTER——customers、orders 是涉及的对象。
语句实际拼装出的结构:必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句;强制子行先有父行的 REFERENCES 外键守卫。
常见问题
这里用到哪些关系?
customers、orders。
核心语句
CREATE TABLE customers (
id bigint NOT NULL,
region text NOT NULL,
name text NOT NULL,
PRIMARY KEY (id, region)
) PARTITION BY LIST (region);
CREATE TABLE customers_eu PARTITION OF customers FOR VALUES IN ('eu');
CREATE TABLE customers_us PARTITION OF customers FOR VALUES IN ('us');
代码示例
CREATE TABLE customers (
id bigint NOT NULL,
region text NOT NULL,
name text NOT NULL,
PRIMARY KEY (id, region)
) PARTITION BY LIST (region);
CREATE TABLE customers_eu PARTITION OF customers FOR VALUES IN ('eu');
CREATE TABLE customers_us PARTITION OF customers FOR VALUES IN ('us');
INSERT INTO customers VALUES
(1, 'eu', 'ada'),
(2, 'us', 'bob');
-- 分区表的唯一约束必须包含分区键,因此外键也要带上 region 两列组合
CREATE TABLE orders (
id int GENERATED ALWAYS AS IDENTITY,
customer_id bigint NOT NULL,
customer_region text NOT NULL,
amount numeric NOT NULL
);
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id, customer_region)
REFERENCES customers (id, region);
INSERT INTO orders (customer_id, customer_region, amount) VALUES
(1, 'eu', 42.00);
-- 引用不存在的 (customer_id, region) 组合会被立即拒绝
-- INSERT INTO orders (customer_id, customer_region, amount) VALUES (9, 'eu', 1.00);
-- ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_fk"