簡體   English   中英

如何在表中插入默認值的行?

[英]How to insert a row to table which has a default value in column?

我有這樣的表:

--
-- PostgreSQL database dump
--

SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;

SET search_path = public, pg_catalog;

SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: forum; Type: TABLE; Schema: public; Owner: postgres; Tablespace: 
--

CREATE TABLE forum (
    forum_id integer DEFAULT nextval('seq_forum'::regclass) NOT NULL,
    forum_name character varying NOT NULL,
    group_id integer NOT NULL,
    forum_parent integer DEFAULT (-1)
);


ALTER TABLE public.forum OWNER TO postgres;

--
-- Name: PK_forum; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace: 
--

ALTER TABLE ONLY forum
    ADD CONSTRAINT "PK_forum" PRIMARY KEY (forum_id);


--
-- Name: FK_group; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--

ALTER TABLE ONLY forum
    ADD CONSTRAINT "FK_group" FOREIGN KEY (group_id) REFERENCES groups(group_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: FK_parent; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--

ALTER TABLE ONLY forum
    ADD CONSTRAINT "FK_parent" FOREIGN KEY (forum_parent) REFERENCES forum(forum_id);


--
-- PostgreSQL database dump complete
--

如上所示,此表在forum_parent列中具有(至少應具有...)默認值。 我想向該表中插入一些數據,我這樣做是這樣的:

INSERT INTO forum (forum_name, group_id) VALUES('new forum', 1); 

是的,我有一個id = 1的組。但是這段代碼給了我:

PostgreSQL error: 23503 ERROR:  insert or update on table "forum" violates foreign key constraint "FK_parent"
DETAIL:  Key (forum_parent)=(-1) is not present in table "forum".

NOTICE:  there is no transaction in progress

如何使它正確?

您的INSERT語句是正確的。 當您未在INSERT語句上顯式聲明列名時,表中插入的值為默認值( 在您的情況下為-1 )。

但是問題在於引用約束。 forum forum_parent ”列取決於同一表的“ forum_id ”列的值。 就像這個DDL所說的,

ALTER TABLE ONLY forum
       ADD CONSTRAINT "FK_parent" FOREIGN KEY (forum_parent) 
       REFERENCES forum(forum_id);

INSERT語句在執行期間失敗,因為在forum_id列上不存在值-1

我的建議是將默認值從-1更改為NULL

CREATE TABLE forum 
(
    forum_id integer DEFAULT nextval('seq_forum'::regclass) NOT NULL,
    forum_name character varying NOT NULL,
    group_id integer NOT NULL,
    forum_parent integer DEFAULT NULL
);

之間的區別NULL-1NULL簡直是不明。 -1為現有數值時不存在該值。

您添加了以下約束:

ALTER TABLE ONLY forum
 ADD CONSTRAINT "FK_parent" FOREIGN KEY (forum_parent) REFERENCES forum(forum_id);

基本上說,forum_parent必須匹配forum_id的現有值。 您可能沒有forum_id = -1的行,因此它失敗了。

您需要創建一個帶有forum_id = -1的行,然后才能使用該默認值...

另一個選擇是將默認值設置為null,因為forum_parent是可為空的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM