I am a new one in postgreSQL. I have 3 tables, one table references the other 2 table's primary keys. But I couldn't able to insert data into the Table3. See the code below :
DROP TABLE Table1 CASCADE;
CREATE TABLE Table1(
"DataID" bigint NOT NULL DEFAULT '0',
"AdData" integer DEFAULT NULL,
PRIMARY KEY ("DataID")
);
DROP TABLE IF EXISTS Table2 CASCADE;
CREATE TABLE Table2 (
"Address" numeric(20) NOT NULL DEFAULT '0',
"Value" numeric(20) DEFAULT NULL,
PRIMARY KEY ("Address")
);
DROP TABLE IF EXISTS Table3 CASCADE;
CREATE TABLE table3 (
"ID" bigint NOT NULL DEFAULT '0',
"DataID" bigint DEFAULT NULL,
"Address" numeric(20) DEFAULT NULL,
"Data" bigint DEFAULT NULL,
PRIMARY KEY ("ID"),
FOREIGN KEY ("DataID") REFERENCES Table1("DataID") on delete cascade on update cascade,
FOREIGN KEY ("Address") REFERENCES Table2("Address") on delete cascade on update cascade
);
ERROR: insert or update on table "Table3" violates foreign key constraint "Table3_DataID_fkey" DETAIL: Key (DataID)=(27856) is not present in table "Table1".
When I trying to insert data into the 3 tables, an error occured. I refer the postgreSQL documentation and change my code as follows: (Unfortunately it shows another error)
DROP TABLE Table1 CASCADE;
CREATE TABLE Table1(
"DataID" bigint NOT NULL DEFAULT '0',
"AdData" integer DEFAULT NULL,
PRIMARY KEY ("DataID")
);
DROP TABLE IF EXISTS Table2 CASCADE;
CREATE TABLE Table2 (
"Address" numeric(20) NOT NULL DEFAULT '0',
"Value" numeric(20) DEFAULT NULL,
PRIMARY KEY ("Address")
);
DROP TABLE IF EXISTS Table3 CASCADE;
CREATE TABLE table3 (
"ID" bigint NOT NULL DEFAULT '0',
"DataID" bigint DEFAULT NULL REFERENCES Table1 ON DELETE RESTRICT,
"Address" numeric(20) DEFAULT NULL REFERENCES Table2 ON DELETE CASCADE,
"Data" bigint DEFAULT NULL,
PRIMARY KEY ("ID"),
PRIMARY KEY("DataID", "Address")
);
ERROR: multiple primary keys for table "Table3" are not allowed LINE 65: PRIMARY KEY("DataID", "Address")
Please help me... How I can create the reference?
I change the ID as UNIQUE and removed the line PRIMARY KEY ("ID"). At that time it shows another error like :
ERROR: duplicate key value violates unique constraint "Table3_pkey"