0

我有这样的表:

--
-- 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

如何使它正确?

4

2 回答 2

3

你的INSERT说法是正确的。当您没有在INSERT语句中明确声明列名时,插入表中的值是默认值(在您的情况下,它是-1)。

但问题在于参照约束。forum_parent表的列forum依赖于forum_id同一个表的列的值。正如这个 DDL 所说,

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

INSERT语句在执行期间失败,因为该值-1不在列上forum_id

我的建议是将默认值从更改-1NULL

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和之间的区别在于根本不-1知道。NULL或该值不存在,-1而是现有数值。

于 2013-01-20T15:10:35.647 回答
2

您添加了以下约束:

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然后才能使用该默认值...

另一种选择是将默认值设置为,因为它可以forum_parent为空

于 2013-01-20T15:09:10.170 回答