我有这样的表:
--
-- 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
如何正确使用?
答案 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
可以为空