如何向表中插入一行中具有默认值的行?

时间:2013-01-20 15:05:57

标签: sql postgresql insert foreign-key-relationship postgresql-9.1

我有这样的表:

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

如何正确使用?

2 个答案:

答案 0 :(得分: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

我的建议是将默认值从-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-1之间的区别在于NULL根本不知道。或-1是现有数值时,该值不存在。

答案 1 :(得分: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创建一行,然后才能使用该默认值...

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