首页 > 解决方案 > Error when inserting data into a database

问题描述

For school we needed to create a database. I wrote the code to create the database but i have problems with inserting data into it. I always get the same error.

ERROR: insert or update on table "gebruikers" violates foreign key constraint "fk_gebruikers_afspeellijsten" DETAIL: Key (userid)=(1) is not present in table "afspeellijsten". SQL state: 23503

I created the "gebruikers" and the "afspeellijsten" tables likes this:

CREATE SCHEMA GROEP10;
CREATE TABLE GROEP10.Gebruikers
(
        userID          INTEGER         PRIMARY KEY,
    name            VARCHAR(45)     NOT NULL,
    wachtwoord      VARCHAR(45)     NOT NULL,
    mail            VARCHAR(45)     UNIQUE  NOT NULL,
    birthDate       DATE            NULL,
    CONSTRAINT fk_Gebruikers_Afspeellijsten FOREIGN KEY ( userID ) REFERENCES GROEP10.Afspeellijsten (userID)
);

CREATE TABLE GROEP10.Afspeellijsten
(
    afspeellijstID  INTEGER         PRIMARY KEY,
    name            VARCHAR(45)     NOT NULL,
    creationDate    DATE            NOT NULL,
    userID          INTEGER         NOT NULL,
    CONSTRAINT fk_Afspeellijsten_Gebruikers UNIQUE ( userID ),
    CONSTRAINT fk_Afspeellijsten_AfspeellijstHasSingle FOREIGN KEY ( afspeellijstID ) REFERENCES GROEP10.AfspeellijstHasSingle ( afspeellijstID )
);

I try to insert data into gebruikers like this:

INSERT INTO gebruikers
VALUES (
    1,
    'Jonas',
    'OK',
    'ZZZ@hotmail.com',
    '03/03/2000'
);

标签: postgresql

解决方案


在您的表中,Gebruikers您有一个FOREIGN KEY CONSTRAINTuserID

CONSTRAINT fk_Gebruikers_Afspeellijsten FOREIGN KEY ( userID ) 
   REFERENCES GROEP10.Afspeellijsten (userID)

这意味着在您可以插入之前,Gebruikers您必须userID = 1Afspeellijsten


推荐阅读