Mysql errno 150 trying to create table with foreign key references

狂风中的少年 提交于 2019-12-22 10:48:41

问题


I'm trying to create a table in mysql with a foreign key reference, like this:

In database A:

CREATE TABLE replication (
  id varchar(255) NOT NULL PRIMARY KEY,
  uid varchar(255) NOT NULL,
  value int(11) NOT NULL,
  FOREIGN KEY (uid) REFERENCES databaseB.users(username)
);

In database B i have a table named users like this:

+-----------------+--------------+------+-----+---------+-------+
| Field           | Type         | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| id              | varchar(255) | NO   |     | NULL    |       |
| username        | varchar(255) | NO   | PRI | NULL    |       |
+-----------------+--------------+------+-----+---------+-------+

When i try to create table replication, gives me the following error:

ERROR 1005 (HY000): Can't create table 'databaseA.replication' (errno: 150)

Any idea? Thanks in advance!


回答1:


You need to add an index to uid or you will not be able to set it up to reference anything.

Also, typically in your DatabaseB you would have your users table have a Primary Key on ID and a unique index on username. Then you would set up a foreign key from DatabaseA.replication REFERENCES databaseB.users(id)




回答2:


you cant make reference key with two different types

in databaseA is integer uid and databaseB is varchar

try this

  FOREIGN KEY (uid) REFERENCES databaseB.users(id)



回答3:


Are both databases of the same type (MyISAM, INNODB)? You cannot point a foreign key to a MyISAM DB. This error can also occur when you are mixing types for the field type (which is the same in this case, varchar(255)), or when the encodings of the fields are different. Another reason could be that you don't have access to the other database.




回答4:


Thetype of the field in a foreign key must be the same as the type of the column they're referencing.I think this problem error because type of the field in a foreign key is different from the column they're referencing. Your foreign key field is uid and referencing table your field is username.Here is the problem.Try to use same type of field in both table like

 FOREIGN KEY (uid) REFERENCES databaseB.users(id)

Hope you understand and works for you.



来源:https://stackoverflow.com/questions/16609548/mysql-errno-150-trying-to-create-table-with-foreign-key-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!