Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a unique key ( not a primary key) be a foreign key to other table?

I have two table students and studentsprofilepic 'username' from students is unique key of the table it is referenced as foreign key for the 'studentsprofilepic' table

the DDL for the tables are

CREATE TABLE students (
  id             NUMBER,
  username       VARCHAR2(30),
  password       VARCHAR2(30),
  firstname      VARCHAR2(30),
  lastname       VARCHAR2(40),
  email          VARCHAR2(300),
  dob            VARCHAR2(20),
  alt_email      VARCHAR2(300),
  street_address VARCHAR2(50),
  address_2      VARCHAR2(50),
  city           VARCHAR2(30),
  state          VARCHAR2(30),
  zip            VARCHAR2(10),
  country        VARCHAR2(60),
  telephone      VARCHAR2(10),
  CONSTRAINT student_id_pk PRIMARY KEY (id),
  CONSTRAINT student_username_uk UNIQUE (username)
);

CREATE TABLE studentsprofilepic (
  id       NUMBER,
  photo_id NUMBER,
  photo    BLOB,

  PRIMARY KEY (photo_id),
  FOREIGN KEY (username) REFERENCES students (username)
);
like image 567
Kamlesh Sharma Avatar asked Feb 15 '15 15:02

Kamlesh Sharma


1 Answers

YES, The foreign key column establishes a direct relationship with a primary key or unique key column (referenced key) usually in another table:

CREATE TABLE BOOK(
    BNAME VARCHAR2(10)NOT NULL UNIQUE,
    BTYPE VARCHAR2(10));
CREATE TABLE BOOKS_AUTH(
    A_ID INT NOT NULL,
    BNAME_REF VARCHAR2(10) NOT NULL,
    FOREIGN KEY (BNAME_REF) REFERENCES BOOK (BNAME));

SQLFIDDLE DEMO

like image 147
nil Avatar answered Sep 17 '22 23:09

nil