两张表建立无主键-外键关系(ORACLE)

Establishin a relation between two tables without the primary key - foreign key relation (ORACLE)

我有以下两个table:

房间数:

ID_Rooms PK number, 
RoomNumber number, 
COD_RoomType number, 
RoomPrice number,
Floor number

D_ROOMTYPE:

ID_d_RoomType PK number,
RoomType varchar2,
COD_RoomType number

第一个 table 存储有关酒店房间的信息,第二个存储房间类型的编码(双人间、三人间、家庭间等)。第二个table中的数据将用于识别第一个中的房间类型。

我需要在两个 table 之间建立关系,但不是基于 primary/foreign 键关系,而是基于出现在两者中的 COD_RoomType 列。

我试过了:

ALTER TABLE rooms
ADD CONSTRAINT rooms_FK1 FOREIGN KEY (COD_RoomType) REFERENCES d_RoomType(COD_RoomType) enable; 

但我收到以下错误报告:

Error report:
SQL Error: ORA-02270: no matching unique or primary key for this column-list 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

有什么方法可以在不使用 primary/foreingn 键的情况下在 COD_RoomType 列上的两个 table 之间建立关系?如果是这样,我还必须做哪些其他修改,SQL 代码会是什么样子?

谢谢, 卡林

如果我理解得很好,您需要对引用的 table:

进行唯一约束
SQL> CREATE TABLE rooms
  2  (
  3      ID_Rooms        NUMBER PRIMARY KEY,
  4      RoomNumber      NUMBER,
  5      COD_RoomType    NUMBER,
  6      RoomPrice       NUMBER,
  7      FLOOR           NUMBER
  8  );

Table created.

SQL> CREATE TABLE D_ROOMTYPE
  2  (
  3      ID_d_RoomType    NUMBER PRIMARY KEY,
  4      RoomType         VARCHAR2(100),
  5      COD_RoomType     NUMBER
  6  );

Table created.

SQL> ALTER TABLE D_ROOMTYPE ADD CONSTRAINT UNIQUE_COD_RoomType UNIQUE  (COD_RoomType);

Table altered.

SQL> ALTER TABLE rooms
  2  ADD CONSTRAINT rooms_FK1 FOREIGN KEY (COD_RoomType) REFERENCES d_RoomType(COD_RoomType) ENABLE;

Table altered.

但是,在大多数情况下,最好根据引用 table 的 PK 添加 FK,而不是对引用 table[=11= 中的代码进行反规范化]