简体   繁体   中英

postgresql key contraint fault

I try to create code for postgresql

CREATE TABLE kaart (
    kaartid integer NOT NULL,
    naam character varying,
    saldo real,
    kaarthouderid integer
);


CREATE TABLE kaart_product (
    kaartkaartid integer,
    productid2 integer
);

CREATE TABLE kaarthouder (
    id integer NOT NULL,
    naam character varying(255),
    naw character varying(255),
    geslacht "char"
);

CREATE TABLE product (
    naam character varying,
    id integer NOT NULL
);


ALTER TABLE ONLY kaart
    ADD CONSTRAINT kaart_pkey PRIMARY KEY (kaartid);

ALTER TABLE ONLY kaarthouder
    ADD CONSTRAINT kaarthouder_pkey PRIMARY KEY (id);

ALTER TABLE ONLY product
    ADD CONSTRAINT product_pkey PRIMARY KEY (id);

ALTER TABLE ONLY kaart
    ADD CONSTRAINT kaartco FOREIGN KEY (kaartid) REFERENCES kaarthouder(id) ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE ONLY kaart_product
    ADD CONSTRAINT kaartkaartidco FOREIGN KEY (kaartkaartid) REFERENCES kaart(kaartid) ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE ONLY kaart_product
    ADD CONSTRAINT productidco FOREIGN KEY (kaartkaartid) REFERENCES product(id) ON UPDATE CASCADE ON DELETE CASCADE;

INSERT INTO kaart VALUES (1, 'Sander',50.00 ,1);
INSERT INTO kaart_product VALUES (1,1);
INSERT INTO kaarthouder VALUES (1, 'Sander','test,testing','man');
INSERT INTO product VALUES ('studentenproduct',1);

But whenever i try to run it it gives me this error:

23503: insert or update on table "kaart" violates foreign key constraint "kaartco"

But i really dont know why this happens since it is the same to the other foreign keys that are below it

So can someone help me fix this?

You try to link to a product and a kaart that doesn't exist yet.

Move:

INSERT INTO kaart_product VALUES (1,1);

Two lines down under:

INSERT INTO product VALUES ('studentenproduct',1);

That should do the job for you. Try to search google for forgein key contstraints and how they work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM