所以我在Oracle中编写了一些代码,并建立了以下表格:
CREATE TABLE users
(
user_id NUMBER NOT NULL,
email_address VARCHAR2(50) NOT NULL UNIQUE,
first_name VARCHAR2(10) NOT NULL,
last_name VARCHAR2(10) NOT NULL,
CONSTRAINT users_pk PRIMARY KEY (user_id)
)
CREATE TABLE product
(
product_id NUMBER,
product_name VARCHAR2(50) NOT NULL,
CONSTRAINT product_pk PRIMARY KEY (product_id)
)
CREATE TABLE downloads
(
download_id NUMBER,
user_id NUMBER NOT NULL,
product_id NUMBER NOT NULL,
download_date DATE NOT NULL,
filename VARCHAR2(50) NOT NULL,
CONSTRAINT downloads_pk PRIMARY KEY (download_id),
CONSTRAINT downloads_fk
FOREIGN KEY(user_id) REFERENCES users (user_id),
CONSTRAINT downloads_fk2
FOREIGN KEY(product_id) REFERENCES product(product_id)
)
CREATE SEQUENCE user_id_seq
CREATE SEQUENCE download_id_seq
CREATE SEQUENCE product_id_seq
downloads表连接用户和产品表,包含外键user_id和product_id。我试图通过以下代码将数据插入下载表:
INSERT INTO downloads (download_id,user_id,product_id,download_date,filename)
VALUES(download_id_seq.NEXTVAL,1,2, SYSDATE, 'one_horse_town.mp3')
INSERT INTO downloads (download_id,user_id,product_id,download_date,filename)
VALUES(download_id_seq.NXTVAL, 2, 1, SYSDATE, 'pedals_are_falling.mp3')
INSERT INTO downloads (download_id,user_id,product_id,download_date,filename)
VALUES(download_id_seq.NEXTVAL, 2, 2, SYSDATE, 'random_song.mp3')
Oracle然后给出了以下错误:
错误报告 - ORA-02291:违反了完整性约束(BC29369.DOWNLOADS_FK2) - 找不到父密钥。
我不确定为什么会出现这种情况,因为在我看来,我已经清楚地标明了我应该的主要和外键关系。有谁知道如何解决这一问题?提前谢谢!
答案 0 :(得分:2)
约束
CONSTRAINT downloads_fk FOREIGN KEY(user_id) REFERENCES users (user_id)
和
CONSTRAINT downloads_fk2 FOREIGN KEY(product_id) REFERENCES product(product_id)
意味着user_id
值1和2,您尝试插入product_id
表的downloads
值1和2必须已存在于users
表中且product
表。
如果users
和product
表在将这些值插入downloads
表之前未填充这些值(1和2),则会出现此错误,因为完整性约束将被侵犯。
您正在创建没有父记录的孤儿记录。这正是您确保在创建这两个约束时不会发生的事情。