wil*_*lvv 5 sql database-design circular-dependency
我看到大多数人都讨厌在数据库设计中有循环依赖.由于在大多数数据库引擎中对此的支持是"棘手的",我想知道这种设计是否有办法:
我有一个用户表和一张图片表
每张图片都有一个userId(插入它的用户)每个用户都有一张个人资料图片
我可能只是创建一个ProfilePictures表,但它会在其他一些地方引起问题(如图片评论).
我知道还有一些与此问题有关的其他问题,但它们与父子关系更相关,而这种情况并非如此.
那么,在这里使用循环依赖是否可以?如果没有,你会如何避免它?
表之间没有循环引用:
User
------
userid NOT NULL
PRIMARY KEY (userid)
Picture
---------
pictureid NOT NULL
userid NOT NULL
PRIMARY KEY (pictureid)
UNIQUE KEY (userid, pictureid)
FOREIGN KEY (userid)
REFERENCES User(userid)
ProfilePicture
---------
userid NOT NULL
pictureid NOT NULL
PRIMARY KEY (userid)
FOREIGN KEY (userid, pictureid) --- if a user is allowed to use only a
REFERENCES Picture(userid, picture) --- picture of his own in his profile
FOREIGN KEY (pictureid) --- if a user is allowed to use any
REFERENCES Picture(picture) --- picture in his profile
Run Code Online (Sandbox Code Playgroud)
与此设计和您的需求的唯一区别在于用户可能没有与他相关联的个人资料照片.
使用表之间的循环引用:
User
------
userid NOT NULL
profilepictureid NULL --- Note the NULL here
PRIMARY KEY (userid)
FOREIGN KEY (userid, profilepictureid) --- if a user is allowed to use only a
REFERENCES Picture(userid, pictureid) --- picture of his own in his profile
FOREIGN KEY (profilepictureid) --- if a user is allowed to use any
REFERENCES Picture(pictureid) --- picture in his profile
Picture
---------
pictureid NOT NULL
userid NOT NULL
PRIMARY KEY (pictureid)
UNIQUE KEY (userid, pictureid)
FOREIGN KEY (userid)
REFERENCES User(userid)
Run Code Online (Sandbox Code Playgroud)
该profilepictureid可设置为NOT NULL但你必须要处理的鸡和蛋的问题,当你想插入到两个表.这可以在一些DBMS中解决,比如PostgreSQL和Oracle - 使用延迟约束.