Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

mysql - Supports transactions, row-level locking, and foreign keys

For some reason I cannot create this table:

CREATE TABLE user_role (
  user_id VARCHAR(20) NOT NULL,
  role_id INTEGER UNSIGNED NOT NULL,

  FOREIGN KEY (user_id)
    REFERENCES users(user_id),
  FOREIGN KEY (role_id)
    REFERENCES roles(role_id)
);

The following similar table has no problems:

CREATE TABLE role_perm (
  role_id INTEGER UNSIGNED NOT NULL,
  perm_id INTEGER UNSIGNED NOT NULL,

  FOREIGN KEY (role_id)
    REFERENCES roles(role_id),
  FOREIGN KEY (perm_id)
    REFERENCES permissions(perm_id)
);

The error message I'm getting is:

#1005 - Can't create table 'test.user_role' (errno: 150) (Details...) Supports transactions, row-level locking, and foreign keys

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed.

If is rather difficult to guess as you didn't provide the definitions for the roles and permissions tables but to paraphrase the doc...

  • ...in order to have a foreign key on a column, you must have an index on the "target" column.
  • ...in order to have a foreign key on a column, both "source" and "target" columns must have the same type (incl. the same size if applicable).
  • ...in order to have a foreign key on a column, both tables must use InnoDB engine.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...