PostgreSQL:PgAdmin 上具有 3 个主键的 table 的外键

PostgreSQL: Foreign Key to a table with 3 Primary Keys on PgAdmin

我有一个名为 table2 的 table,它有 3 个 PK、categoryid、languageid 和 unitid。我正在尝试从 table1 到 table2 进行 FK。但是由于下一个错误,我无法添加 FK 约束:

英语:"ERROR there´s not an unique restriction whitch coincides with the columns taken on units table"

Table 2:

Table 1:

约束条件:

PSQL

table 2(单位)

                              Tabla ½public.units╗
       Columna       |       Tipo       | Ordenamiento | Nulable  | Por omisi¾n
---------------------+------------------+--------------+----------+-------------
 unitdisplayname     | text             |              |          |
 unitdescription     | text             |              |          |
 unitid              | integer          |              | not null |
 conversionfactor    | double precision |              |          |
 typesystem          | text             |              |          |
 prefixfactor        | integer          |              |          |
 categorydisplayname | text             |              |          |
 categoryid          | integer          |              | not null |
 languageid          | text             |              | not null |
═ndices:
    "units_pkey" PRIMARY KEY, btree (unitid, categoryid, languageid)

我正在尝试的 SQL 句子:

CREATE TABLE public.units_sensores
(
    id_rel integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 ),
    obra integer NOT NULL,
    edificio_serverguid integer NOT NULL,
    categoryid integer NOT NULL,
    unitid integer NOT NULL,
    PRIMARY KEY (id_rel),
    CONSTRAINT obras FOREIGN KEY (obra)
        REFERENCES public.obras (id_obra) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT edificios_serverguid FOREIGN KEY (edificio_serverguid)
        REFERENCES public.edificios_trend_meta (id_edificio) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT categoryid FOREIGN KEY (categoryid)
        REFERENCES public.units (categoryid) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT unitid FOREIGN KEY (unitid)
        REFERENCES public.units (unitid) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
);

ALTER TABLE public.units_sensores
    OWNER to postgres;

摘要:

我想知道如何将其写入 postgreSQL:

reate Table A (
    A_ID char(3) primary key,
    A_name char(10) primary key,
    A_desc desc char(50)
)

create Table B (
    B_ID char(3) primary key,
    B_A_ID char(3),
    B_A_Name char(10),
    constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)

您无法创建该外键约束,因为 units(category_id).

上没有唯一约束

对于外键,您需要在目标列上精确定义的 PRIMARY KEYUNIQUE 约束。此约束标识目标行。

包含额外列的唯一约束还不够好,因为目标 table 中可能还有不止一行具有相同的 category_id

由于 table 只能有一个主键约束,因此您必须使用 UNIQUE 约束。要获得与主键相同的效果,该列也应该是 NOT NULL(在您的 table 中已经是这种情况)。

示例:

ALTER TABLE units
   ADD UNIQUE (category_id);

添加这些约束可能会使主键变得多余。在这种情况下,您可以删除它并将新约束之一设为主键。