MySQL 关系表和主键数据类型
我正在构建一个 MySQL 数据库,该数据库将包含许多相关表。我知道我可以创建一个唯一且自动递增的主键,然后将该主键引用为相关表中的外键。我的问题是主/外键数据类型(int、varchar 等)的最佳实践是什么。我想确保我第一次就做对了。
谢谢
I'm working on building a MySQL database that will have many related tables. I know I can create a primary key that is unique and auto increments, then reference that Primary Key as a Foreign Key in the related table. My question is what are best practices for Primary/Foreign key data types (int, varchar, etc..). I want to make sure I get this right the first time.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MySQL 中最常用的数据类型是 INT UNSIGNED。它的长度为 4 个字节,最多可存储 40 亿个数字,这对于大多数应用程序来说已经足够了。刚开始使用应用程序时,使用 BIGINT(8B - 18446744073709551615 范围)通常是一种过度杀伤力。在您的数据库变得对于 INT 主键来说太大之前,您无论如何都需要聘请专业的 DBA 来帮助您解决其他问题。
当使用 GUID 类型主键时,可以使用 CHAR 或 BINARY 数据类型 - 这样的键可以更轻松地跨多个数据库实例分片数据,但是使用 MySQL 时,更常见的是多主复制。
使用 InnoDB 表时,最好记住,PK 将隐式地成为在特定表上创建的所有其他索引中的最后一列。这使得使用相当短的数据类型进行 PK 变得很重要(同样,4B INT 通常可以很好地完成其工作)。
In MySQL most commonly used datatype is INT UNSIGNED. It's 4 bytes long and can store numbers up to 4 billion which is more than enough for majority of applications. Using BIGINT (8B - 18446744073709551615 range) is usually an overkill when just starting with your application. Before your database gets too large for INT primary key, you'll need to hire a professional DBA anyway to help you with other issues.
CHAR or BINARY datatypes can be used, when GUID type Primary key is used - such keys make it easier to shard data across multiple database instances, however with MySQL a multi master replication is more often seen.
When using InnoDB tables it's good to remember, that PK will be implicitly the last column in all other indexes created on specific table. This makes it important to use reasonably short datatype for PK (again 4B INT usually does its job well).