改变我在表中的PK

发布于 2024-11-05 22:28:54 字数 351 浏览 1 评论 0原文

如果我有一个名为 university 的表,有两个字段,一个用于 id_university,即 PK,另一个用于 name_of_university。每个大学的名称都是唯一的,不能重复。

在这种情况下,我可以删除id_university,并将name_of_university作为主键,对吗?

像这样的东西:

university
-----------------------
pk name_of_university

感谢

If i have a table called university, with two fields, one for id_university, that is PK and other for name_of_university. Each name of university is unique and cannot be repeated.

In this case i can remove the id_university, and put the name_of_university as Primary key, correct?

Something like this:

Table

university
-----------------------
pk name_of_university

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

完美的未来在梦里 2024-11-12 22:28:54

你可以这样做,但你不应该这样做。大学的名称是商业关键,因此可能会发生变化。识别候选主键的标准之一是它们应该是不变的。

因此,最佳实践是拥有一个代理(合成)主键,用于外键等,并维护对业务键的唯一约束。因此,好消息是,您当前的数据模型已接近最佳实践。只需在名称列中添加一个唯一的值即可。

 alter table university
      add constraint uni_name_uk unique (name_of_university);

You can do this but you shouldn't. The name of the university is a business key, and as such is liable to change. One of the criteria for identifying candidate primary keys is that they should be invariant.

So, best practice is to have a surrogate (synthetic) primary key, for use in foreign keys, etc and maintain a unique constraint on the business key. So, the good news is, your current data model is close to being best practice. Just add a unique on the name column and you're good to go.

 alter table university
      add constraint uni_name_uk unique (name_of_university);
行至春深 2024-11-12 22:28:54

最好将主键保留为 id_university,并在 name_of_university 上添加唯一索引。

It's good practice to leave the primary key as id_university and just add a unique index on name_of_university.

晨曦慕雪 2024-11-12 22:28:54

是的,正确的。

但不推荐。
长时间的PK会让一切都慢下来,慢很多。

在 InnoDB 上,PK 包含在每个辅助键上,这将使您的表膨胀。
连接会更慢,插入会更慢,排序会更慢。
而且你的桌子会更大。
这是一个非常糟糕的主意:-抱歉,

让你的 PK 尽可能短并自动增量(如果可能的话),这将导致快速、愉快的代码。

Yes correct.

But not recommended.
Long PK's slow everything down, way way down.

And on InnoDB the PK is included on every secondary key, this will balloon your table.
Join's will be slower, inserts will be slower, sorts will be slower.
And your tables will be bigger.
It's a really bad idea :-Sorry

Keep your PK as short as possible and autoincrement (if possible), this will result in snappy, happy code.

我为君王 2024-11-12 22:28:54

是的,这是正确的。钥匙就是钥匙。如果您有不止一把钥匙,那么您将哪把钥匙称为您的主钥匙并没有真正的区别。重要的是您打算实施和使用它们的方式。

Yes that's correct. A key is a key. If you have more than one key then it makes no real difference which key you call your primary one. What matters is the way you intend to implement and use them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文