Question

i want to make a table in MySQL server with mediumtext column as UNIQUE KEY

CREATE TABLE `parts` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` mediumtext NOT NULL,
      `display_status` int(11) NOT NULL,
       UNIQUE KEY `name` (`name`),
       PRIMARY KEY (`id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

but this made an error

    BLOB/TEXT column 'name' used in key specification without a key length

when I change the type of `name` to varchar .. it works!

can you tell if i can to make text column as UNIQUE KEY

Était-ce utile?

La solution

Basically you can not use Text column as UNIQUE key. Because practically such a big column will not be unique and there might be a chance of more duplicates. So go for hashing method and use that output as a UNIQUE constraint.

Autres conseils

The limit of 255 for varchar length no longer applies. From the documentation:

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions.

Unique indexes must have a known maximum length (a requirement of mysql due to its internal implementation), so use varchar with a large enough value to fit your longest expected value, eg

...
`name` varchar(65535) NOT NULL, -- for example 
...

I know this is very old but in case anyone else wants to, you can make a varchar or text column unique, you just have to do it after the table creation.

 DROP TABLE IF EXISTS meeting;
CREATE TABLE meeting (
    meeting_id int(11) UNSIGNED UNIQUE NOT NULL PRIMARY KEY AUTO_INCREMENT,
    meeting_name varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL
);
CREATE UNIQUE INDEX meeting ON meeting(meeting_name);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top