且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试使用外键引用创建表的Mysql errno 150

更新时间:2022-11-08 18:36:26

你需要添加一个索引到uid,否则你将无法设置它来引用任何东西。

另外,通常在你的DatabaseB中,你的用户表有一个主键ID和一个唯一的用户名索引。然后你可以设置一个来自DatabaseA.replication的外键参考databaseB.users(id)


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!

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)