Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Option 3, though it may feel strange, is the closest to what you want to model. You'd do something like:</p> <pre><code>User { UserId PRIMARY KEY (UserId) } Computer { ComputerId, PrimaryUserId PRIMARY KEY (UserId) FOREIGN KEY (ComputerId, PrimaryUserId) REFERENCES Computer_User (ComputerId, UserId) } Computer_User { ComputerId, UserId PRIMARY KEY (ComputerId, UserId) FOREIGN KEY (ComputerId) REFERENCES Computer (ComputerId) FOREIGN KEY (UserId) REFERENCES User (UserId) } </code></pre> <p>Which gives you 0 or 1 primary user (the PrimaryUserId can be nullable if you want), that must be in Computer_User. Edit: If a user can only be primary for 1 computer, then a UNIQUE CONSTRAINT on Computer.PrimaryUserId will enforce that. Note that there is no requirement that all users be a primary on some computer (that would be a 1:1 relationship, and would call for them to be in the same table).</p> <p>Edit: Some queries to show you the simplicity of this design</p> <pre><code>--All users of a computer SELECT User.* FROM User JOIN Computer_User ON User.UserId = Computer_User.UserId WHERE Computer_User.ComputerId = @computerId --Primary user of a computer SELECT User.* FROM User JOIN Computer ON User.UserId = Computer.PrimaryUserId WHERE Computer.ComputerId = @computerId --All computers a user has access to SELECT Computer.* FROM Computer JOIN Computer_User ON Computer.ComputerId = Computer_User.ComputerId WHERE Computer_User.UserId = @userId --Primary computer for a user SELECT Computer.* FROM Computer WHERE PrimaryUserId = @userId </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload