唯一键(不是主键)可以成为其他 table 的外键吗?

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

我有两个 table students 和 studentsprofilepic 'username' 来自学生是 table 的唯一键 它被引用为 'studentsprofilepic' table

的外键

table 的 DDL 是

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)
);

YES,外键列与primary keyunique key列建立直接关系(引用键)通常在另一个 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 演示

是的,为什么不呢。可以在 FOREIGN KEY 中引用 UNIQUE constraint

您可能有一个主键和一个唯一键,并且您想要验证两者。

是的,您可以引用一个或多个受主键约束或唯一约束约束的列。

您的 table "studentsprofilepic" 的问题是您的外键尝试使用列 "studentsprofilepic"。"username",但该列不存在。

create table studentsprofilepic(
  id number,
  photo_id number,
  photo blob,
  -- Add the "username" column.
  username varchar2(30) not null,
  primary key (photo_id),
  foreign key (username) references students (username)
);

此外,问问自己“"studentsprofilepic"."id" 有什么意义?”它不是主键。它不是外键。它似乎没有 任何 目的,除了让你说 "Hey, my table has a column named 'id'!" 这是一个有问题的功能。

考虑添加更多 not null 约束。