← 中文资源

简体中文版本

复合外键 MATCH FULL 与 MATCH SIMPLE

复合外键默认 MATCH SIMPLE:引用列含 NULL 就整组跳过校验,留下半悬挂行;MATCH FULL 要求全空或全非空,从源头拒绝这种数据。

阅读英文原文

实现说明

实际执行的是 INSERT / CREATE——invoices、line_items_simple、line_items_full 是涉及的对象。 机制上由这些部分组成:必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;强制子行先有父行的 REFERENCES 外键守卫。

常见问题

这些语句涉及哪些表?

invoices、line_items_simple、line_items_full。

核心语句

CREATE TABLE line_items_full (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number) MATCH FULL
);
CREATE TABLE line_items_simple (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number)
);
CREATE TABLE invoices (
    year     int,
    number   int,
    customer text NOT NULL,
    PRIMARY KEY (year, number)
);

代码示例

-- 发票主键是两列复合;明细表用复合外键引用
CREATE TABLE invoices (
    year     int,
    number   int,
    customer text NOT NULL,
    PRIMARY KEY (year, number)
);

-- MATCH SIMPLE(默认):引用列只要有 NULL,整组校验被跳过
CREATE TABLE line_items_simple (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number)
);

-- MATCH FULL:要求引用列全 NULL 或全非 NULL,杜绝“半个引用”
CREATE TABLE line_items_full (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number) MATCH FULL
);

INSERT INTO invoices VALUES (2026, 1001, 'Acme');

-- MATCH SIMPLE 接受这种只有年份、没有票号的半悬挂行
INSERT INTO line_items_simple VALUES (2026, NULL, 25.00);

-- MATCH FULL 拒绝同样的行:
-- ERROR: insert or update on table "line_items_full"
--        violates foreign key constraint
INSERT INTO line_items_full VALUES (2026, NULL, 25.00);