VARCHAR作为外键/主键在数据库中好还是坏? [英] VARCHAR as foreign key/primary key in database good or bad?

查看:1059
本文介绍了VARCHAR作为外键/主键在数据库中好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用ID nr:s而不是VARCHARS作为外键,更好?
并且最好使用ID nr:s是否作为主键的VARCHARS?
通过ID nr我的意思是INT!



这是我现在的

 类别表:
cat_id(INT)(PK)
cat_name(VARCHAR)

类别选项表:
option_id(INT)(PK)
car_id(INT)(FK)
option_name(VARCHAR)

我可能有这个想法:

 类别表:
cat_name(VARCHAR)(PK)

类别选项表:
cat_name(VARCHAR)(FK)
option_name(VARCHAR)(PK)
解决方案

div>

VARCHAR用于任何KEY的问题是它们可以保存WHITE SPACE。空白空间由任何非屏幕可读字符组成,如空格选项卡,回车等。使用VARCHAR作为键可以使您的生活困难,当你开始寻找为什么表不返回的记录与额外的空间在结束



当然,您 CAN 可以使用VARCHAR,但您必须非常小心输入和输出。



整数类型有一个包含10个字符的有效列表, 0,1, 2,3,4,5,6,7,8,9



您可以使用基于整数的键,并使用VARCHAR作为UNIQUE值,如果您希望拥有更快的查找。


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!

This is what I have now:

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

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

I COULD HAVE THIS I THINK:

category table:
cat_name (VARCHAR) (PK)

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

Or am I thinking completely wrong here?

解决方案

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.

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.

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.

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作为外键/主键在数据库中好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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