简体   繁体   中英

Primary Key and Foreign key in same table

I am using SQL Server 2014 and Entity Framework code-first. I am trying to create a table Account Master which will have the details of the customer and columns are as below.

  • Id as autoincrement primary key
  • Name as varchar
  • City as varchar
  • phonenumber as varchar
  • BrokerId as int

Now my question is how refer to the BrokerId as foreign key to the same table name Account Master with the primary key on column Id .

Because in my case broker will be also having all this details. As well as it is not necessary that every customer will have broker. Whether I should do like this or not.

Thanks in advance.

Could you add a Foreign Key constraint to your CREATE TABLE statement?

CONSTRAINT FK_AccMaster_ID FOREIGN KEY (BrokerID)
  REFERENCES AccountMaster(ID)

This is a common way to link two tables together. Unless I am missing something in your question...

I'm answering to the part "Whether I should do like this or not."

Please consider creating two separate tablets User and Broker. Memory wise that's almost same even if User and Broker have same details.

If will provide extensibility to both your tables. Capable of Many to Many relationships.

Also good design implies to let one table represent single entity. To query brokers you don't want to scan your Users and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM