Limit the value of a MySQL datatype to a specific range (preferably not ENUM)

一曲冷凌霜 提交于 2019-11-27 15:44:11

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!