How to set 1 to 0…1 relationship in SQL Server Management Studio

╄→尐↘猪︶ㄣ 提交于 2019-12-12 02:49:06

问题


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


回答1:


If you have these requirements:

  • a User can be Professor - or not
  • a Professor is always a User

then you are correct that it's a 1 :: 0..1 relationship. In SQL, it can be implemented like this:

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

From what you describe, you probably have defined the foreign key constraint in reverse order.




回答2:


I think you are should use foreign key here. Professor ID should be the foreign key in the user table, that will solve all your problem.

Just look up what foreign key is and how to write foreign key query




回答3:


In the professors table you should create a ProfessorID and add the UserID as a FK nullable.



来源:https://stackoverflow.com/questions/19349055/how-to-set-1-to-0-1-relationship-in-sql-server-management-studio

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