我有這樣的表:如何將行插入列中具有默認值的表中?
--
-- 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
如何使對的?
好吧,現在我明白了,但有另一個關聯的問題。我該怎麼做:我的子論壇可以有一個父母(其他論壇),然後subforums'forum_parent'列指出其他論壇ID。但也有可能是一個論壇沒有父母(導致它的論壇,而不是一個子論壇,這就是爲什麼'forum_parent'應該是-1)? – Katie
不,論壇的默認值應該是'NULL'而不是'-1',所以將模式更改爲'forum_parent integer DEFAULT NULL'。查詢它很容易,順便說一下,當你只想顯示論壇而不是子論壇時,只需使用'WHERE forum_parent IS NULL'。 –
我這樣做:'alter table forum ALTER COLUMN forum_parent SET default null;'thanks!:) – Katie