A relation table is the common solution to representing a many-to-many (m:n) relationship.
In the simplest form, it combines foreign keys referencing the two relating tables to a new composite primary key:
A AtoB B ---- ---- ---- *id *Aid *id data *Bid data
How should it be indexed to provide optimal performance in every JOIN situation?
- clustered index over (
Aid ASC, Bid ASC) (this is mandatory anyway, I guess) - option #1 plus an additional index over (
Bid ASC, Aid ASC) - or option #1 plus an additional index over (
Bid ASC) - any other options? Vendor-specific stuff, maybe?
I made some tests, and here is the update:
To cover all possible cases, you’ll need to have:
This will cover all
JOINsutiations ANDORDER BYNote that an index on
Bis actually sorted on(B, A)since it references clustered rows.As long as your
aandbtables havePRIMARY KEY‘s on id’s, you don’t need to create additional indexes to handleORDER BY ASC, DESC.See the entry in my blog for more details: