Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

sql server - How to handle nullable primary key that references two tables

I have a database with three tables, call them foo, bar and baz. Each instance of bar references an instance of baz, although there may be instances of baz not referenced in the bar table. In most cases, an instance of foo will reference an instance of bar (and therefore can be mapped to an instance of baz.) However in some cases an instance of foo will reference the baz table directly.

Possible ERD

In a simplified version where the foo-baz relationship doesn't exist, I can easily make barid part of the primary key for the foo table, which is what I'd like to do here, except that barid will occasionally be null.

Therefore a sample from the foo table might look like this:

fooid    barid    bazid
    1        1     NULL
    2        2     NULL
    3     NULL        9
    4       17     NULL

The issue is how to handle creating a primary key for the foo table. Should I be using unique indexes instead of a constraint? I could also create dummy instances of bar for the purpose of connecting the foo and baz tables. In that case I might add an isreal field so I know when this is the case. I'm sure someone can tell me why this is a bad idea though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is not straightforward answer to this question without understanding the application and the implementation.Please see below the other permutations created for relations amongst the table.

fooid    barid    bazid
    1        1     NULL
    2        2     NULL
    3     NULL        9
    4       17     NULL
    5       18     6
    6       14     6
    6       18     10

Generic answer to the question is please do not create dummy values , instead the bar id primary key will be the fooid only. And add a unique constraint if the fooid,barid and bazid is always going to be unique.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...