简体   繁体   中英

How do I create a check to make sure a value exists in another table?

Right now I have two tables, one that contains a compound primary key and another that that references one of the values of the primary key but is a one-to-many relationship between Product and Mapping . The following is an idea of the setup:

CREATE TABLE dev."Product"
(
  "Id" serial NOT NULL,
  "ShortCode" character(6),
  CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
)

CREATE TABLE dev."Mapping"
(
  "LookupId" integer NOT NULL,
  "ShortCode" character(6) NOT NULL,
  CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
)

Since the ShortCode is displayed to the user as a six character string I don't want to have a another table to have a proper foreign key reference but trying to create one with the current design is not allowed by PostgreSQL . As such, how can I create a check so that the short code in the Mapping table is checked to make sure it exists?

Depending on the fine print of your requirements and your version of Postgres I would suggest a TRIGGER or a NOT VALID CHECK constraint .

We have just discussed the matter in depth in this related question on dba.SE:

If I understand you correctly, you need a UNIQUE constraint on "Product"."ShortCode". Surely it should be declared NOT NULL, too.

CREATE TABLE dev."Product"
(
  "Id" serial NOT NULL,
  "ShortCode" character(6) NOT NULL UNIQUE,
  CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
);

CREATE TABLE dev."Mapping"
(
  "LookupId" integer NOT NULL,
  "ShortCode" character(6) NOT NULL REFERENCES dev."Product" ("ShortCode"),
  CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
);

Your original "Product" table will allow this INSERT statement to succeed, but it shouldn't.

insert into dev."Product" ("ShortCode") values
(NULL), (NULL), ('ABC'), ('ABC'), ('ABC');

Data like that is just about useless.

select * from dev."Product"
id  ShortCode
--
1   
2   
3   ABC   
4   ABC   
5   ABC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM