Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Management Studio - adding foreign key confusing?

I always find it confusing to add foreign keys to primary table in Management Studio.

Lets say I have a

Table1  {     ID int, -- Primary Key     Table2ID int, -- Refers to Table2's ID  }  Table2  {     ID int, -- Primary Key     SomeData nvarchar(50) } 

I am adding a foreign key to Table1 by Right Click -> Relationships -> Table and column specification. I am setting "Primary" popups to Table2, ID and "Foreign Key Table" to Table1, Table2ID.

My questions:

  1. Shouldn't Table2 be listed for "Foreign Key Table" and Table1 for Primary Key? Is my understanding wrong?

  2. When I save I get an alert "The following tables will be saved to your database." and it shows both tables. I really don't get this. I only changed Table1. Why is the second table shown?

like image 334
tvr Avatar asked Oct 09 '10 08:10

tvr


People also ask

Why foreign key is not recommended?

Having active foreign keys on tables improves data quality but hurts performance of insert, update and delete operations. Before those tasks database needs to check if it doesn't violate data integrity. This is a reason why some architects and DBAs give up on foreign keys at all.

Do adding foreign keys make queries faster?

Yes it will improve the performance of you db if you are checking integrity using foreign key instead of running many queries for checking the record is exist in database in your program. Show activity on this post. For MySQL 5.7, it definitely can speed up queries involving multiple joins amazingly well!

How do you decide where to put foreign key?

When you join the two tables together, the primary key of the parent table will be set equal to the foreign key of the child table. Whichever one is not the primary key is the foreign key. In one-to-many relationships, the FK goes on the "many" side.


1 Answers

  • Click the expand symbol next to the table.
  • Right click on the "Keys" folder and select "New Foreign Key."
  • (Alternatively, you can click the Relationships button on the toolstrip when you have the table open)
  • Click the "..." button on the "Tables and Columns Specifications" row to open the editor.
  • The drop down on the left will be the table you're adding from, and the static text field will list the table you're adding to.
  • Use the dropdowns to specify your constraints, and be sure both sides have the same number of columns.
like image 81
Zach Avatar answered Oct 15 '22 02:10

Zach