Domanda

I am creating 3 tables in MySQL (Users, linkPosts, replyPosts)

The first two tables are executed fine, but I got an error when I am trying to insert the SQL of the replyPosts. The following is the SQL code of the three tables:

The first table SQL code: works fine

CREATE TABLE Users ( 
userName VARCHAR (20) NOT NULL PRIMARY KEY,
password VARCHAR (20),
firstName VARCHAR (200),
lastName VARCHAR (200),
bio VARCHAR (160),
email VARCHAR (200),
country VARCHAR (200)
); 

The code of the second table: works fine

CREATE TABLE linkPosts ( 
linkPostID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
link VARCHAR(255),
linkDescription VARCHAR (140), 
linkPostTime TIMESTAMP,
userName VARCHAR (20),
FOREIGN KEY (userName) REFERENCES Users(userName));

The third table where the error appears:

CREATE TABLE replyPosts ( 
replyPostID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
reply VARCHAR (140), 
replyPostTime TIMESTAMP,
userName VARCHAR (20),
linkPostID INT,
FOREIGN KEY (linkPostID) REFERENCES linkPosts(linkPostID),
FOREIGN KEY (userName) REFERENCES Users(userName));

The error I got as follows:

Error 1005 : Can't create table 'mdb_aa847.replyPosts' (errno: 150)

I have searched and tried other people's solutions but never worked. Any one can figure out where the error is?

Thanks in advance..

È stato utile?

Soluzione

Does table replyPosts already exist? This error can happen in case you have duplicate foreign key names. use perror with the errno (in your case, its error 150), you should get:

MySQL error code 150: Foreign key constraint is incorrectly formed

After looking at your complete SQL, I think it is down to the fact that linkPostID is INT UNSIGNED when you create LinkPosts table, whereas in ReplyPosts table, linkPostID is INT. Change that to INT UNSIGNED and see if it works.

As per the document here "foreign keys" should have the same size and sign, if it's integer.

As a side note, I would still insist on using UserId as primary key on Users table instead of UserName. Every time you insert a record in Users table, it will be sorted by UserName (since it is primary key, hence clustered index). Bigger the UserName field (Varchar(20)), the longer it takes for sorting the whole table. As your table grows, inserting records into User table is going to get cumbersome.

Altri suggerimenti

This is due to the foreign key constraint

and since you are using FOREIGN KEY (userName) REFERENCES Users(userName) which is a varchar, it is not possible in MYSQL to make a foreign reference on varchar

You can drop the foreign key constraint of the userName, and try with userId

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top