简体   繁体   English

如何创建检查以确保另一个表中存在值?

[英]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 . 现在,我有两个表,一个表包含一个复合主键,另一个表引用了主键的值之一,但是是ProductMapping之间的一对多关系。 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 . 由于ShortCode是作为六个字符串显示给用户的,我不想让另一个表具有适当的外键引用,但是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? 这样,如何创建检查以检查“ Mapping表中的短代码以确保其存在?

Depending on the fine print of your requirements and your version of Postgres I would suggest a TRIGGER or a NOT VALID CHECK constraint . 根据您的要求和Postgres的版本,建议使用TRIGGERNOT VALID CHECK约束

We have just discussed the matter in depth in this related question on dba.SE: 我们刚刚在dba.SE上的相关问题中深入讨论了此问题:

If I understand you correctly, you need a UNIQUE constraint on "Product"."ShortCode". 如果我对您的理解正确,则需要在“产品”。“ ShortCode”上使用UNIQUE约束。 Surely it should be declared NOT NULL, too. 当然也应该将其声明为NOT NULL。

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语句成功执行,但不会成功。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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