Conditional foreign key in SQL

前端 未结 3 1021
时光取名叫无心
时光取名叫无心 2021-02-05 14:37

i have one table called as PartyChannel having following columns

 ID, ChannelID, ChannelType

ChannelID stores MailID

相关标签:
3条回答
  • 2021-02-05 15:08

    You can use PERSISTED COMPUTED columns with a case statement but in the end, it buys you nothing but overhead.

    The best solution would be to model them as three distinct values to start with.

    CREATE TABLE Mails (MailID INTEGER PRIMARY KEY)
    CREATE TABLE Phones (PhoneID INTEGER PRIMARY KEY)
    CREATE TABLE Emails (EmailID INTEGER PRIMARY KEY)
    
    CREATE TABLE PartyChannel (
      ID INTEGER NOT NULL
      , ChannelID INTEGER NOT NULL
      , ChannelType CHAR(1) NOT NULL
      , MailID AS (CASE WHEN [ChannelType] = 'M' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Mails (MailID)
      , PhoneID AS  (CASE WHEN [ChannelType] = 'P' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Phones (PhoneID)
      , EmailID AS  (CASE WHEN [ChannelType] = 'E' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Emails (EmailID)
    )
    

    Disclaimer

    just because you can doesn't mean you should.

    0 讨论(0)
  • 2021-02-05 15:12

    AFAIK, you cannot do this with standard foreign keys. However, you could implement something to help ensure data integrity by using triggers. Essentially, the trigger would check for the presence of a "foreign key" on the referenced table - the value that must be present - whenever there is an insert or update on the referencing table. Similarly, a delete from the referenced table could have a trigger that checks for records on the referencing table that use the key being deleted.

    Update: Although I went right for the "answer" I agree with the comment left by @onedaywhen that this is actually a design-caused problem that should probably make you reconsider your design. That is, you should have three different columns rather than one column referencing three tables. You would just leave the other two columns null when one is filled which, in turn, would let you use standard foreign keys. Any concern that this would "use too much space" is silly; it represents a severe case of premature optimization - it just isn't going to matter.

    0 讨论(0)
  • 2021-02-05 15:21

    Sub-type Email, Mail, Phone to the Channel.

    alt text

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