I’ve two tables which are connected to each other through a one to many relation.
the problem is that the referenced table also has a foreign key of the second table!
I know it’s confusing, So I’ll show you a simple design of my database:
Authors
AuthorId Name DefaultBookId (FK)
-------- ------- -------------
1 John 1
2 Mike 3
3 Mig 5
Books
BookId Title AuthorId (FK)
-------- ------- -------------
1 TitleInfo1 1
2 TitleInfo2 3
3 TitleInfo3 2
4 TitleInfo4 1
5 TitleInfo5 3
6 TitleInfo6 3
7 TitleInfo7 1
Of course I have to make the AuthorId in the books table a foreign key and that’s the normal case, but now I need to set a default book for every author so I’ll define a foreign key on a new column (DefaultBookId) to specify the default book for each writer.
Now, both tables are dependent on each other so I can’t delete any item unless I remove the relation between them and it doesn’t feel the right thing to do!
Any ideas on whether this design flawed or not and what can I do about it ?
I would implement this with a 3rd table that joins the other two. You’d end up with:
Authors
DefaultBook
Books
By putting a UNIQUE constraing on
DefaultBook.AuthorIdyou can prevent each author from having more than one default. If you need to delete an author, simply delete his default and any books associated with him, then you can delete the author.The one problem this has is that it’s hard to enforce that each author has a default book, but that requirement is what led you to this problem in the first place.