我无法从PostGres DB的父表中删除记录。你们中的任何一个都可以让我对此有所了解。
-- Table: tbl_patient
-- DROP TABLE tbl_patient;
CREATE TABLE tbl_patient
(
patient_id bigserial NOT NULL,
date_of_birth date NOT NULL,
fathers_name character varying(255) NOT NULL,
first_name character varying(255) NOT NULL,
last_name character varying(255),
marital_status character varying(255),
mobile_number character varying(255) NOT NULL,
occupation character varying(255),
phone_number character varying(255),
pregnancy_status character varying(255),
sex character varying(255) NOT NULL,
CONSTRAINT tbl_patient_pkey PRIMARY KEY (patient_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE tbl_patient
OWNER TO postgres;
-- Table: tbl_address
CREATE TABLE tbl_address
(
address_id bigserial NOT NULL,
address_line_1 character varying(255) NOT NULL,
address_line_2 character varying(255),
city character varying(255),
country character varying(255),
district character varying(255) NOT NULL,
pincode character varying(255) NOT NULL,
state character varying(255),
street character varying(255),
patient_id bigint,
CONSTRAINT tbl_address_pkey PRIMARY KEY (address_id),
CONSTRAINT fk_slc6pgeimmox5buka8bydy6c4 FOREIGN KEY (patient_id)
REFERENCES tbl_patient (patient_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE tbl_address
OWNER TO postgres;
// --------------------------------------------- ----------------------
当我输入此命令时
DELETE FROM tbl_patient
WHERE patient_id = 1;
我在下面遇到此错误
错误:表“tbl_patient”上的更新或删除违反了外键 表“tbl_address”SQL上的约束“fk_slc6pgeimmox5buka8bydy6c4” 状态:23503详细信息:Key(patient_id)=(1)仍被引用 表“tbl_address”。
答案 0 :(得分:2)
你写DELETE NO ACTION
,你想要行动:)只需要改为
REFERENCES tbl_patient (patient_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
NO ACTION
表示服务器不会对引用的行(如果存在)执行任何操作。由于它们存在并且您还将MATCH SIMPLE
指定为一列外键,因此PostgreSQL无法执行删除,因为该引用的行。