数据库表总是有主键吗? [英] Should a database table always have primary keys?

查看:198
本文介绍了数据库表总是有主键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在我的数据库表中总是有一个主键吗?

Should I always have a primary key in my database tables?

让我们进行SO标记。您可以在任何修订版本中看到标记,它可能位于带有postID和修订版本号的tag_rev表中。我需要一个PK吗?

Let's take the SO tagging. You can see the tag in any revision, its likely to be in a tag_rev table with the postID and revision number. Would I need a PK for that?

也因为它是一个rev表,并且当前不使用标签应该是一个tagID,而不是多个post_id的多个条目tagid pair?

Also since it is in a rev table and not currently use the tags should be a blob of tagIDs instead of multiple entries of multiple post_id tagid pair?

推荐答案

您应该努力在任何非平凡的表格中建立主键,通过该密钥访问(或更新或删除)单个记录。主键可以由多个列组成,正式来说,将是最短的可用超级键;

You should strive to have a primary key in any non-trivial table where you're likely to want to access (or update or delete) individual records by that key. Primary keys can consist of multiple columns, and formally speaking, will be the shortest available superkey; that is, the shortest available group of columns which, together, uniquely identify any row.

我不知道Stack Overflow数据库模式是什么样子(以及从一些我在Jeff的博客上阅读的东西,我不想),但是在你描述的情况下,完全有可能在帖子标识符,修订号和标签值之间有一个主键;当然,这将是最短的(也是唯一的)超级密钥可用。

I don't know what the Stack Overflow database schema looks like (and from some of the things I've read on Jeff's blog, I don't want to), but in the situation you describe, it's entirely possible there is a primary key across the post identifier, revision number and tag value; certainly, that would be the shortest (and only) superkey available.

对于你的第二点,虽然可能是合理的,表,它违背了表中每个行/列交叉应该包含一个单一值的原则。虽然它可能会稍微简化开发,但没有理由不能保存到带有版本元数据的规范化表,即使对于作为标签的小东西也是如此。

With regards to your second point, while it may be reasonable to argue in favour of aggregating values in archive tables, it does go against the principle that each row/column intersection in a table ought to contain one single value. While it may slightly simplify development, there is no reason you can't keep to a normalised table with versioned metadata, even for something as trivial as tags.

这篇关于数据库表总是有主键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆