VARCHAR 作为数据库中的外键/主键好还是坏?

VARCHAR as foreign key/primary key in database good or bad?(VARCHAR 作为数据库中的外键/主键好还是坏?)
本文介绍了VARCHAR 作为数据库中的外键/主键好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 ID nr:s 而不是 VARCHARS 作为外键会更好吗?使用 ID nr:s isstead of VARCHARS 作为主键是否更好?通过 ID nr 我的意思是 INT!

Is it better if I use ID nr:s instead of VARCHARS as foreign keys? And is it better to use ID nr:s isntead of VARCHARS as Primary Keys? By ID nr I mean INT!

这就是我现在所拥有的:

category table:
cat_id ( INT ) (PK)
cat_name (VARCHAR)

category options table:
option_id ( INT ) (PK)
car_id ( INT ) (FK)
option_name ( VARCHAR ) 

我可以这么认为:

category table:
cat_name (VARCHAR) (PK)

category options table:
cat_name ( VARCHAR ) (FK)
option_name ( VARCHAR ) ( PK )

还是我的想法完全错了?

Or am I thinking completely wrong here?

推荐答案

VARCHAR 用于任何 KEY 的问题是它们可以容纳 WHITE SPACE.空白由任何非屏幕可读字符组成,例如空格制表符、回车符等.当您开始追查为什么表不返回带有额外空格的记录时,使用 VARCHAR 作为键会使您的生活变得困难他们的钥匙.

The problem with VARCHAR being used for any KEY is that they can hold WHITE SPACE. White space consists of ANY non-screen-readable character, like spaces tabs, carriage returns etc. Using a VARCHAR as a key can make your life difficult when you start to hunt down why tables aren't returning records with extra spaces at the end of their keys.

当然,您可以使用 VARCHAR,但是您必须非常小心输入和输出.它们还会占用更多空间,并且在执行查询时可能会更慢.

Sure, you CAN use VARCHAR, but you do have to be very careful with the input and output. They also take up more space and are likely slower when doing a Queries.

整数类型有一个包含 10 个有效字符的小列表,0,1,2,3,4,5,6,7,8,9.它们是用作密钥的更好的解决方案.

Integer types have a small list of 10 characters that are valid, 0,1,2,3,4,5,6,7,8,9. They are a much better solution to use as keys.

如果您想获得更快查找的优势,您可以始终使用基于整数的键并使用 VARCHAR 作为 UNIQUE 值.

You could always use an integer-based key and use VARCHAR as a UNIQUE value if you wanted to have the advantages of faster lookups.

这篇关于VARCHAR 作为数据库中的外键/主键好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)