2012-11-01 49 views
0

我有這樣的表:如何將值插入到具有默認值的列中? [PostgreSQL的9.1]

CREATE TABLE employee (
    id INTEGER DEFAULT NEXTVAL('ids'::regclass) NOT NULL, 
    name CHARACTER VARYING NOT NULL, 
    employer INTEGER DEFAULT (-1) 
); 

我想做某事插入到這個表(我想離開employer默認,-1):

INSERT INTO employee (name, id) VALUES('Doe', 2); 

但我的PostgreSQL 9.1抱怨:

ERROR: insert or update on table "employee" violates foreign key constraint "FK_employer" 
DETAIL: Key (employer)=(-1) is not present in table "employer". 

我知道那裏有ID爲任何僱主= -1,但仍然,我想用那種方式。我想爲這個emplyee設置僱主-1。 postgreSQL有可能嗎?

+5

您在該列上定義了外鍵,因此您無法插入不存在於被引用表中的ID。如果你想表示僱主是「未知的」,那麼將其設置爲「空」,而不是一些「魔術」價值。這正是'null'的意思。 –

回答

2

使默認值爲空。好嗎?

employer INTEGER DEFAULT null 
+0

不是真的......當我想要做'select'時,我想從表中得到-1不爲NULL :( – Katie

+0

@Katie'當僱主爲null時選擇案例-1僱員的僱主最終僱主' –

+3

@ Katie或使用[COALESCE](http://www.postgresql.org/docs/9.2/static/functions-conditional.html)函數自動將NULL值轉換爲-1,例如,SELECT COALESCE(僱主,-1)' –