Oracle foreign key

寵の児 提交于 2019-12-11 14:49:19

问题


So i have two tables

CREATE TABLE Client(
ID NUMBER(10) NOT NULL, (PRIMARY KEY)
Name VARCHAR(30) NOT NULL,
Surname VARCHAR(30) NOT NULL,
Phone NUMBER(11) NOT NULL,
Email VARCHAR(70));

CREATE TABLE Boss(
B_Surname VARCHAR(30) NOT NULL, (PRIMARY KEY)
B_Name VARCHAR(30) NOT NULL);

I need to put foreign key (B_surname from Boss table) to Client table. I've tried use ALTER TABLE:

ALTER TABLE Client ADD CONSTRAINT Boss_Client_fk FOREIGN KEY (B_Surname) REFERENCES Client(ID);

After that I got errors. Thanks for help.


回答1:


I think you want the following. Please note that you should probably be using VARCHAR2 rather than VARCHAR in Oracle. They work the same at the moment but there is a possibility that Oracle will change the functionality for VARCHAR to bring it in line with the ANSI standard (in which empty strings '' are distinguished from NULLs ... but I digress):

CREATE TABLE client
( id NUMBER(10) NOT NULL PRIMARY KEY
, name VARCHAR2(30) NOT NULL
, surname VARCHAR2(30) NOT NULL
, phone NUMBER(11) NOT NULL
, email VARCHAR2(70) );

CREATE TABLE boss
( b_surname VARCHAR2(30) NOT NULL PRIMARY KEY
, b_Name VARCHAR2(30) NOT NULL );

And then:

ALTER TABLE client ADD CONSTRAINT boss_client_fk FOREIGN KEY (surname) REFERENCES boss (b_surname);

It's a bit odd that the column is named surname in CLIENT and b_surname in BOSS.

If you want b_surname in BOSS to refer to surname in CLIENT -- then you need to make CLIENT.surname a primary key, or at least unique.



来源:https://stackoverflow.com/questions/28014800/oracle-foreign-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!