mysql限制类别_将MySQL数据类型的值限制在特定范围(最好不是ENUM)

bd96500e110b49cbb3cd949968f18be7.png

I want to limit the datatype value that can be stored within a field to a specific range of integer values: [0,10].

On user input within a PHP script I validate and sanitise the data to make sure it is within the range 0 to 10. However, is there a way to ensure this remains true within the votes table itself via some sort of datatype or constraint?

At the moment I store the int value within an UNSIGNED TINYINT which of course has the range of 0-255. I am aware of ENUM as an option. However, I have read that it is not advisable when using numbers: http://komlenic.com/244/8-reasons-why-mysqls-enum-data-type-is-evil/

The SQL:

CREATE TABLE votes (

vote_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,

article_id MEDIUMINT UNSIGNED NOT NULL,

user_id MEDIUMINT UNSIGNED NOT NULL,

user_vote TINYINT UNSIGNED NOT NULL,

PRIMARY KEY (vote_id),

FOREIGN KEY (article_id) REFERENCES articles (article_id) ON DELETE CASCADE ON UPDATE NO ACTION,

FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE NO ACTION,

CONSTRAINT article_uservoted UNIQUE KEY (user_id, article_id),

INDEX vote_value (article_id, user_id, user_vote)

) ENGINE=INNODB;

I hope someone can assist.

解决方案

You can create a table of allowed vote values and add a foreign key in your votes table, so when you try to insert a vote with user_vote value other than existing in your allowed_votes table you get a constraint fail error:

CREATE TABLE allowed_votes (

vote_rank TINYINT UNSIGNED NOT NULL,

PRIMARY KEY (vote_rank)

) ENGINE = InnoDB;

INSERT INTO allowed_votes( vote_rank ) VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);

ALTER TABLE votes

ADD FOREIGN KEY (user_vote) REFERENCES allowed_votes (vote_rank);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值