In SQL Server 2008, do relationships make queries

2020-03-24 07:21发布

问题:

For example, if I have a BlogPosts table, and a PostCategory table, where the BlogPosts table has a FK field PostCategoryId. Would a relationship make the query faster, or is it more of a data quality thing?

What about when a join table is involved? Take the PostCategoryId field out of the BlogPosts table, and have a table "between" them called PostsInCategories, which has only 2 FK fields: BlogPostId and PostCategoryId, combined for form a PK.

Do relationships improve queries there?

回答1:

Foreign key relationships are about enforcing data integrity, e.g. making sure you don't have any "voodoo" child rows that don't have a parent row anymore, and so forth.

Foreign key relationships on their own do not boost your performance since SQL Server will not create any indices automatically for foreign keys.

For several reasons (boost performance when enforcing referential integrity and increase JOIN performance - see Kimberly Tripp's blog post on the topic) it is very much a recommended step to add indices to all foreign key fields in your tables - and adding those indices will speed up queries that will use those FK relationships.