gpt4 book ai didi

sql - 主键和外键问题

转载 作者:行者123 更新时间:2023-12-04 18:30:45 24 4
gpt4 key购买 nike

嗨,我对引用文献有疑问

ALTER TABLE POZYCJA_FAKTURY
ADD (CONSTRAINT FK_ASD FOREIGN KEY (ID_Pozycji)
references FAKTURA (ID_Pozycji))
Error report -
ORA-02270: niezgodność klucza unikatowego lub głównego dla tej listy kolumn
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
catalog view

create table FAKTURA
(
ID_Faktury number(9) not null,
ID_Naprawy number(9) not null,
ID_Pozycji number(9) not null,
ID_Osoby_Pracownik number(9) not null,
ID_Osoby_Klient number(9) not null,
NR_Faktury number(9) not null,
Data_Faktury date not null,

constraint PK_FAKTURA primary key (ID_Faktury)

);

create table POZYCJA_FAKTURY
(
ID_Pozycji number(9) not null,
Ilosc number(10) not null,

constraint PK_POZYCJA_FAKTURY primary key (ID_Pozycji)

);


ALTER TABLE POZYCJA_FAKTURY
ADD CONSTRAINT FK_FAKTURA_POZYCJA_FAKTURY FOREIGN KEY (ID_Pozycji)
REFERENCES FAKTURA (ID_Pozycji);

你知道哪里出了问题吗?

谢谢。

最佳答案

您正在尝试添加指向 FAKTURA 表上的 ID_Pozycji 列的外键:

FOREIGN KEY (ID_Pozycji) references FAKTURA (ID_Pozycji)

但这不是那个表上的键,ID_Faktury 是:

constraint PK_FAKTURA primary key (ID_Faktury)

外键必须指向目标表上的键。例如:

FOREIGN KEY (ID_Faktury) references FAKTURA (ID_Faktury)

这就是它在目标表中识别记录的方式。 ID_Faktury 列标识一个 FAKTURA 记录,因此任何需要外键返回到 FAKTURA 的表都需要引用 ID_Faktury在那张 table 上。 (虽然外键列本身不需要具有相同的名称,但为了避免混淆通常是个好主意。)


相反,可能至少引用一个唯一列(如果不是主键)。我不是 Oracle 专家,但这条消息至少暗示了这一点:

A REFERENCES clause in a CREATE/ALTER TABLE statement gives a column-list for which there is no matching unique or primary key constraint in the referenced table.

虽然我仍然建议从数据建模的角度使用主键作为引用点,但您的 RDBMS 可能只支持向唯一字段添加外键。但首先 FAKTURA 表中的字段必须是唯一的:

CONSTRAINT U_ID_Pozycji UNIQUE (ID_Pozycji)

关于sql - 主键和外键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com