How to model Several-to-many relationship in database? -


it's not many-to-many relationship. example: have user table , role table. constraint user can have 0-5 roles , role can assigned many users.

how model in database? thanks

edit: i'm looking standard solution on database side model. there similar scenarios above. example: user password history: 1 user have max 10 previous passwords stored in pwd_history table. it's kind of one-to-(0-10) relationship.

but seems me there no standard solution on database side. (@branko's solution (2) below looks though. ) guess best practice model enforce on client side, making these numbers configurable in property file , implementing client logic handle this.

there 3 strategies:

  1. just model normal many-to-many in database, enforce limit in triggers or (less ideally) client code.

  2. model many-to-many, place additional constraints limit number of rows:

    enter image description here

    check (role_no in (1, 2, 3, 4, 5))

    the combination of unique constraint u1 on {user_id, role_no} , above check ensures there cannot more 5 user_role rows belonging same user.

  3. simply have 5 null-able 1-to-many relationships:

    enter image description here


out of these strategies, first instinct go (2) - it's "cleanest" , lends easy modification, should limits ever change.

the (3) might more performant in scenarios (although might slower in others) awkward work , less flexible.

the (1) pain implement - you'll have locking avoid concurrency issues , destroy scalability in process.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -