简体   繁体   中英

What would be an appropriate table/database design for these constraints?

Given 4 tables,

table 'base'

  • has an id column (primary key)

table 'instance'

  • has an id column (primary key)
  • has a base_id column (foreign key to table 'base')

table 'modifier'

  • has an id column (primary key)
  • for simplicity sake, assume 2 column defining min and max.

table 'base_has_modifier'

  • has a base_id column (foreign key to table 'base')
  • has a modifier_id column (foreign key to table 'modifier')

The constraint I am trying to model is, an instance can only have modifiers tied to its base.

Currently I have this,

table 'instance_has_base_modifier'

  • has instance_id (from 'instance')
  • has base_id (from 'base_has_modifier')
  • has modifier_id (from 'base_has_modifier')
  • for simplicity sake, assume 1 column containing value between min and max, as defined under table 'modifier'

As you can see, this allows instance to have modifiers from other bases.

Now the question, is it possible to model this in a way that enforces an instance to only have modifiers tagged to its base? If so, how? If not, why?

Thank you.

-- Base BAS exists.
--
base {BAS}
  PK {BAS}
-- Base BAS has instance number INS#, of that base.
--
instance_ {BAS, INS#}
       PK {BAS, INS#}

FK1 {BAS} REFERENCES base {BAS}
-- Modifier MOD exists.
--
modifier {MOD}
      PK {MOD}
-- Modifier MOD applies to base BAS
--
base_mod {BAS, MOD}
      PK {BAS, MOD}

FK1 {BAS} REFERENCES base     {BAS}
FK2 {MOD} REFERENCES modifier {MOD}

Option 1

If a base modifier applies to all instances of that base.

-- Modifier MOD applies to instance number INS# of base BAS.
--
CREATE VIEW inst_mod
AS
SELECT i.BAS
     , i.INS#
     , b.MOD
FROM instance_  AS i
JOIN base_mod   AS b ON b.BAS = i.BAS ;

Option 2

If a base modifier may, or may not, apply to instances of that base.

-- Modifier MOD applies to instance number INS# of base BAS.
--
inst_mod {BAS, INS#, MOD}
      PK {BAS, INS#, MOD}

FK1 {BAS, INS#} REFERENCES instance_ {BAS, INS#}
FK2 {BAS, MOD}  REFERENCES base_mod  {BAS, MOD}

Note:

All attributes (columns) NOT NULL

PK = Primary Key
FK = Foreign Key

Using suffix # to save on screen space.
OK for SQL Server and Oracle, for others use _NO.
For example, rename INS# to INS_NO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM