我可以使用VARCHAR作为主键吗? [英] Can I use VARCHAR as the PRIMARY KEY?

查看:1245
本文介绍了我可以使用VARCHAR作为主键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于存储优惠券/折扣的表,我想使用coupon_code列作为主键,它是VARCHAR.

I have a table for storing coupons/discounts, and I want to use the coupon_code column as the primary key, which is a VARCHAR.

我的基本原理是,每个优惠券都将具有唯一的代码,而我将要运行的唯一命令是SELECT ... FROM ... WHERE coupon_code='..'

My rationale is that, each coupon will have a unique code, and the only commands I will be running are SELECT ... FROM ... WHERE coupon_code='..'

我将不进行任何联接或索引编制,并且我看不到该表中有超过几百个条目.

I won't be doing any joins or indexing, and I don't see there ever being more than a few hundred entries in this table.

在我看来这可以,但是我不知道是否有任何我想念的东西.

It seems to me that this will be OK, but I don't know if there is anything I'm missing/not thinking about.

推荐答案

从RDBMS可以允许的意义上说,您当然可以.但是,您是否应该这样做的答案却有所不同:在大多数情况下,应该选择不具有数据库系统含义的值 作为主键.

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

如果您知道该值在要建模的系统中是唯一的,则可以向表中添加唯一索引或唯一约束.但是,您的主键通常应该是一些无意义"的值,例如自动递增的数字或GUID.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

这样做的理由很简单:确实发生了数据输入错误和对似乎不可更改的事物的不频繁更改.它们变得很难固定用作主键的值.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

这篇关于我可以使用VARCHAR作为主键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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