简体   繁体   English

具有相关表的条件约束

[英]Conditional constraint with related tables

I have a question related to SQL, more specifically to PostgreSQL.我有一个与 SQL 相关的问题,更具体地说是与 PostgreSQL 相关的问题。 I'm currently trying to make some conditional constraints, and I have succeded in making a conditional constraint in a single table.我目前正在尝试制作一些条件约束,并且我已经成功地在单个表中制作了条件约束。 In the example below, I want to make sure that the column cpf is not null only when the column client_type has the value "F".在下面的示例中,我想确保仅当列client_type的值为“F”时,列cpf才不是 null。

CREATE TYPE client_type AS ENUM('F', 'J');

CREATE TABLE clients (
  id SERIAL NOT NULL UNIQUE, 
  name varchar(255), 
  client_type client_type NOT NULL, 
  cpf varchar(11), 
  cnpj varchar(14), 
  CHECK (CASE WHEN client_type = 'F' THEN cpf IS NOT NULL END), 
  CHECK (CASE WHEN client_type = 'J' THEN cnpj IS NOT NULL END)
);

My question is, it is possible to do that with related tables?我的问题是,可以用相关表来做到这一点吗?

For instance: I have a table called aditional_info , that has a foreign key referencing to the clients table, and I want to enforce that some columns of the aditional_info table cannot be null only when the related row in the clients table have a column with the value "F".例如:我有一个名为aditional_info的表,它有一个引用clients表的外键,并且我想强制aditional_info表的某些列只有在clients表中的相关行具有包含值“F”。

I may be trying to do something that is impossible, so if someone could tell me if this is achievable in some way I'll be very grateful!我可能正在尝试做一些不可能的事情,所以如果有人能告诉我这是否可以通过某种方式实现,我将非常感激!

I was able to achieve what I was trying to do with a function.我能够用 function 实现我想要做的事情。 Don't know if this is the best approach, but so far it is working for me.不知道这是否是最好的方法,但到目前为止它对我有用。

The function takes the client id, saves the client type into a variable and return it. function 获取客户端 ID,将客户端类型保存到变量中并返回。

CREATE OR REPLACE FUNCTION checkClientType(int) RETURNS varchar as $$
DECLARE
    type varchar;
BEGIN
    SELECT client_type INTO type FROM clients WHERE id = $1;

    RETURN type;
END;
$$ LANGUAGE plpgsql;

Then I check if the value returned by the function is equal to "J", and if it is, I say that the municipal_registration column cannot be null.然后我检查function返回的值是否等于“J”,如果是,我说city_registration列不能是null。

CREATE TABLE aditional_info (
  id SERIAL NOT NULL UNIQUE,
  client_id int REFERENCES clients(id) ON DELETE SET NULL ON UPDATE CASCADE,
  rg varchar(10) NOT NULL,
  issuing_body varchar NOT NULL,
  birth_date timestamp NOT NULL,
  municipal_registration varchar,
  CONSTRAINT not_null_municipal_registration CHECK(CASE WHEN checkClientType(client_id) = 'J' THEN municipal_registration IS NOT NULL END)
);

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

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