MYSQL, When defining a table does the UNIQUE constraint have to be used in conjunction with an INTEGER or can it be any datatype?

StackOverflow https://stackoverflow.com/questions/6078863

Question

I am wanting to have a label column (VARCHAR) and I want it to be unique, but when I try to create the table it seems to be throwing an error. Can a unique constraint only be used in conjunction with an INTEGER or will it work with other datatypes as well. The error I am getting is (ERRNO 150)

CREATE TABLE IF NOT EXISTS `user`(
user_id INT  NOT NULL    AUTO_INCREMENT  PRIMARY KEY,
username    VARCHAR(50) NOT NULL,
`password`  VARCHAR(255) NOT NULL
);

CREATE TABLE IF NOT EXISTS `element`(
element_id  INT NOT NULL    AUTO_INCREMENT PRIMARY KEY,
label   VARCHAR(5) NOT NULL DEFAULT '',
parent_id   INT NULL,
user_id INT NOT NULL,
created_on  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
edited_on   TIMESTAMP NOT NULL,
UNIQUE(label),
KEY element_1 (label),
CONSTRAINT FK_element_1 FOREIGN KEY (user_id) REFERENCES `user` (user_id),
CONSTRAINT FK_element_2 FOREIGN KEY (parent_id) REFERENCES `element` (element_id)
);
Was it helpful?

Solution

The only way I can have this error, if the first table is created with MyISAM engine and the second (tried to be created) with InnoDB.

Check the definition of the created table user, using:

SHOW CREATE TABLE user ;

If that's the case, drop it and recreate it with:

CREATE TABLE IF NOT EXISTS `user`(
user_id INT  NOT NULL    AUTO_INCREMENT  PRIMARY KEY,
username    VARCHAR(50) NOT NULL,
`password`  VARCHAR(255) NOT NULL
)
 ENGINE = InnoDB ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top