ORA-02270:此列列表帮助没有匹配的唯一键或主键

时间:2016-10-08 11:34:55

标签: oracle foreign-keys constraints

我做了一些这样的表

create table Pembeli(
ID_pembeli number(16) constraint pm_id_p_pk_fk PRIMARY KEY,
Nama_pembeli varchar2(30) constraint pm_nama_pembeli_nn NOT NULL,
Nama_penumpang varchar2(30) constraint pm_nama_penumpang_nn NOT NULL,
Nama_kereta varchar2(30) constraint pm_nama_kereta_nn NOT NULL,
Kelas varchar2(10) constraint pm_kelas_nn NOT NULL
)

create table Kereta(
ID_Kereta number(3) constraint kr_id_kereta_pk_fk PRIMARY KEY,
Nama_Kereta varchar2(30) constraint kr_nama_kereta_nn NOT NULL,
Jam_keberangkatan TIMESTAMP default systimestamp,
Jam_tiba TIMESTAMP default systimestamp,
Stasiun_asal varchar2(20) constraint kr_stasiun_asal_nn NOT NULL,
Stasiun_tujuan varchar2(20) constraint kr_stasiun_tujuan_nn NOT NULL,
Harga number(7) constraint kr_harga_nn NOT NULL
)

create table Kelas(
ID_Pembeli number(16) constraint kl_id_pembeli_pk_fk PRIMARY KEY,
Nama_kelas varchar2(30) constraint kl_nama_kelas_nn NOT NULL,
Harga number (7) constraint kl_harga_nn NOT NULL
)

create table Tiket(
ID_Tiket varchar2(10),
ID_Pembeli number(16),
No_Duduk varchar(3) constraint tk_no_nn NOT NULL,
ID_Kereta number(3),
Kelas varchar2(10) constraint tk_kelas_nn NOT NULL,
Jumlah number(3) constraint tk_jml_nn NOT NULL,
CONSTRAINT tk_pk PRIMARY KEY(ID_Tiket,ID_Pembeli)
)

create table Kasir(
ID_Kasir varchar2(10),
Nama_kasir varchar2(30) constraint ks_nama_kasir_nn NOT NULL,
Uang number(7) constraint ks_uang_nn NOT NULL,
Harga number(7) constraint ks_harga_nn NOT NULL,
Kembalian number(7) constraint ks_kembalian_nn NOT NULL,
ID_Pembeli number(16),
CONSTRAINT ks_pk PRIMARY KEY(ID_Kasir,ID_Pembeli)
)

使用这些外键

alter table Pembeli add constraint pm_fk1 FOREIGN KEY (ID_Pembeli) references kasir(ID_pembeli)

alter table Pembeli add constraint pm_fk2 FOREIGN KEY (ID_Pembeli) references tiket(ID_pembeli)

我可以创建所有表,但是当我尝试向表中添加约束外键时,我遇到了问题:运行alter table命令时出错。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

错误很明显:您正在尝试将一列作为指向具有复合主键(两列)的表的外键。那无能为力。

但是,ID_Pembeli已在Pembeli表中声明为PK。看起来你想让外键反过来:你想改变表kasir和ticket,在两个表中创建ID_Pembeli外键,引用表Pembeli。这会更有意义,也会奏效。只需修复ALTER TABLE语句。