Many to Many Relation Design - Intersection Table Design

后端 未结 11 1428
野的像风
野的像风 2020-12-07 19:20

I\'m wondering what a better design is for the intersection table for a many-to-many relationship.

The two approaches I am considering are:

CREATE TA         


        
相关标签:
11条回答
  • 2020-12-07 19:42

    Answering your second question...

    You just need to add a check constraint, like this:

    CREATE TABLE SomeIntersection 
    (
         ParentRecord INT REFERENCES TableA NOT NULL,
         ChildRecord INT REFERENCES TableA NOT NULL,
         PRIMARY KEY(TableAId, TableBId),
         CHECK (ParentRecord <> ChildRecord)
    )
    
    0 讨论(0)
  • 2020-12-07 19:45

    The second version is the best for me, it avoids the creation of an extra index.

    0 讨论(0)
  • 2020-12-07 19:48

    if you go with the first, just use an IDENTITY on the PK, you don't need to waste the space (disk and memory cache) with a UNIQUEIDENTIFIER .

    0 讨论(0)
  • 2020-12-07 19:50

    If you won't have any additional fields in the intersection table it really doesn't need an ID of its own, and adding one doesn't add any benefit. However, if you're going to be putting other fields into that table, and in many cases you will, it should have its own ID as the primary key.

    Rule of thumb, of course, but there you go.

    0 讨论(0)
  • 2020-12-07 19:51

    What you are building is called an "Intersection".

    I have a very clear memory of my database professor in school saying that an intersection relationship is nearly always an entity in its own right, and so it's normally worth allocating space for it as such. This would indicate that former is more "correct".

    That said, I personally tend to prefer the latter. It really comes down to whether you will ever retrieve one of these records directly or if you'll only use the table when joining on one of the original tables.

    0 讨论(0)
  • 2020-12-07 19:52

    From a developer's perspective view, I prefer the former. It's easier to write and test when dealing with it.

    I don't need to check for two keys to retrieve a unique record.

    0 讨论(0)
提交回复
热议问题