MySQL database with unique fields ignored ending spaces

后端 未结 4 415
别那么骄傲
别那么骄傲 2020-11-29 08:39

My projects requires to start inputs from the user with the spacing on the left and spacing on the right of a word, for example \'apple\'. If the user types in \' apple\' or

4条回答
  •  感情败类
    2020-11-29 09:33

    Thanks to @kennethc. His answer works for me. Add a string length field to the table and to the unique key.

    CREATE TABLE strings
    ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    string varchar(255) COLLATE utf8_bin NOT NULL,
    created_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    string_length int(3),
    PRIMARY KEY (id), UNIQUE KEY string (string,string_length) )
    ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
    

    In MySQL it's possible to update the string length field with couple of triggers like this:

    CREATE TRIGGER `string_length_insert` BEFORE INSERT ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);
    CREATE TRIGGER `string_length_update` BEFORE UPDATE ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);
    

提交回复
热议问题