2

I have tables:

Users{UserId ...}
Professors{UserId ...}

I set UserId to be PK in both tables and made 1:1 relationship.

But if I try to insert new user it doesn't work as it requires insert in the Professor table too.

I want to make that one user can have only 1 record in Professor table but I also want to make it that it doesn't have to exist in Professor table (I don't want to make all users professors :) ).

How to set 1 to (0...1) relationship in SQL Server Management Studio?

I know that set enforce key constraints to NO is not a solution :)

4

3 回答 3

7

如果您有这些要求:

  • 用户可以是教授 - 也可以不是
  • 教授永远是用户

那么你是对的,这是一种1 :: 0..1关系。在 SQL 中,可以这样实现:

CREATE TABLE Users
  ( UserId INT NOT NULL
  , ...
  , PRIMARY KEY (UserId)
  ) ;

CREATE TABLE Professors
  ( UserId INT NOT NULL
  , ...
  , PRIMARY KEY (UserId)
  , FOREIGN KEY (UserId)
      REFERENCES Users (UserId)
  ) ;

根据您的描述,您可能已经以相反的顺序定义了外键约束。

于 2013-10-13T19:16:43.900 回答
0

我认为你应该在这里使用外键。教授 ID 应该是用户表中的外键,这将解决您的所有问题。

只需查找外键是什么以及如何编写外键查询

于 2013-10-13T19:06:47.250 回答
-1

在professors 表中,您应该创建一个ProfessorID 并将UserID 添加为FK 可为空的。

于 2013-10-13T19:06:10.063 回答