當試圖delete duplicates有:如何刪除具有重複值的特定列的行?
DELETE FROM staff
WHERE staff_id NOT IN (SELECT MIN(staff_id) FROM staff GROUP BY store_id);
有一個錯誤:
[23503] ERROR: update or delete on table "staff" violates foreign key constraint "payment_staff_id_fkey" on table "payment" Detail: Key (staff_id)=(3) is still referenced from table "payment".
事實上,支付有FK約束:
CREATE TABLE public.payment
(
payment_id integer NOT NULL DEFAULT nextval('payment_payment_id_seq'::regclass),
customer_id integer NOT NULL,
staff_id smallint NOT NULL,
rental_id integer NOT NULL,
amount numeric(5,2) NOT NULL,
payment_date timestamp without time zone NOT NULL,
CONSTRAINT payment_pkey PRIMARY KEY (payment_id),
CONSTRAINT payment_customer_id_fkey FOREIGN KEY (customer_id)
REFERENCES public.customer (customer_id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT payment_rental_id_fkey FOREIGN KEY (rental_id)
REFERENCES public.rental (rental_id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE SET NULL,
CONSTRAINT payment_staff_id_fkey FOREIGN KEY (staff_id)
REFERENCES public.staff (staff_id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT
)
WITH (
OIDS=FALSE
);
這是不可能的設置payment.staff_id = null
因爲NOT NULL
作爲suggested here。
解決此問題的最簡單方法是什麼?
'WHERE store_id NOT IN(SELECT MIN(staff_id)FROM staff GROUP BY store_id)'這看起來不太好,你正在比較store_ids和staff_ids。 – joop
這意味着您嘗試刪除所有員工,每個商店除一名員工之外。非常不可能這是你真正想要的。 – joop
這正是我需要刪除所有員工,除了每個商店的一名員工,因爲我在Hibernate中有@OneToOne映射,否則失敗。也許我應該修改一些約束條件到'ON DELETE CASCADE DEFERRABLE' ..... –