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

后端 未结 1 1428
不知归路
不知归路 2020-12-03 22:40

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

相关标签:
1条回答
  • 2020-12-03 23:13

    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);
    
    0 讨论(0)
提交回复
热议问题