使用 NULL 外键或指向保留记录?
我正在设计一个包含消息和信使的数据库。
create table Message(
MessageID int,
MessengerID int,
Content nvarchar(max)
)
create table Messenger(
MessengerID int,
MessengerName nvarchar(100)
)
有时,使者身份不明。在这种情况下,您会使用 NULL 值,还是在 Messenger 表中为未知信使保留记录吗?我很想看到一个简短的解释为什么一种解决方案比另一种更好。
I'm designing a database containing messages and messengers.
create table Message(
MessageID int,
MessengerID int,
Content nvarchar(max)
)
create table Messenger(
MessengerID int,
MessengerName nvarchar(100)
)
Sometimes the messenger in unknown. Would you use a NULL value in that case, or a reserved record for unknown messengers in the Messenger table? I'd love to see a short explanation why one solution is better than the other.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用 NULL。
这正是 NULL 存在的目的。说“我不知道它是什么。”
在表中保留保留记录总是很痛苦。你现在必须对你的用户说,嘿,如果你愿意,你可以添加更多的信使,你可以删除它们,你甚至可以修改,但不要删除这一行,那一行。这会导致不必要的复杂化。
I would use NULL.
This is exactly what NULL exists for. To say "I've no idea what it is."
Having a reserved record in a table is always a pain. You now have to say to your users, hey, you can add more messengers if you wish, and you can delete them, and you can even amend, but don't delete this line, and that line, too. This causes unnecessary complications.
两者都不。我会使用另一个表来存储信使信息:(
顺便说一句,我注意到你的所有列都可以为空,并且你的表没有键。我会首先解决这个问题!)
SQL 中的 NULL 并不能准确地表示某些内容的语义“未知”。以这种方式使用它经常会导致矛盾和不正确的结果,如果您设计的表能够准确地模拟数据库应该表示的情况,则没有必要。
不使用可空外键的另一个原因是不同的 DBMS 在其工作方式上存在分歧,并且用户可能无法理解它们或正确使用它们。
Neither. I would use another table for the messenger info:
(I note in passing that ALL your columns are nullable and your tables don't have keys. I would fix that first!)
NULL in SQL does not accurately represent the semantics of something being "unknown". Using it that way frequently leads to contradictions and incorrect results and it isn't necessary if you design tables that accurately model the situation that the database is supposed to represent.
Another reason not to use nullable foreign keys is that different DBMSs disagree on how they work and users probably won't understand them or use them correctly.