【问题标题】:MariaDB foreign key issueMariaDB 外键问题
【发布时间】:2016-04-04 16:09:10
【问题描述】:

自从我不得不创建/定义数据库以来已经有一段时间了,所以请忽略我缺乏理解。基本上,我有一个包含几个字段的表,其中一个是一个散列,它引用另一个具有相同散列的表和散列值。我认为问题在于我使用外键来引用辅助表中的非主键。所以我的问题是:我如何建立这种关系?以下是创建我的问题的最小示例:

-- first table, imagine this as the hash value (should I remove the r_id,
-- and make the r_hash a unique & primary key?)
create table rx(
 r_id int(10) auto_increment primary key,
 r_hash varchar(175) default null,
 r_val  varchar(175) default null
);

create table cx(
 c_id int(10) auto_increment primary key,
 c_name varchar(175) default null,
 querystr varchar(175) default null,
 r_c_hash varchar(175) default null,
 constraint r_fk foreign key(r_c_hash) references rx(r_hash)
);

还有一个我仍然无法解决的经典错误:

ERROR 1005 (HY000): Can't create table 'test2.cx' (errno: 150)

编辑:

为澄清起见,来自 rx 的示例行如下所示:

1 |  asdkjIOFJE93fijflskf | anexamplehashvalue

来自 cx 的示例行可能如下所示:

1 | name_of_file | queryString=yes&1=3 | asdkjIOFJE93fijflskf 

如您所见,哈希值与我所需要的完全匹配。我是否使用哈希作为 PK 重新创建 rx 表并使其唯一?或者我可以保持表格的结构吗?

【问题讨论】:

  • 如果rx 是键值对存储,这只是问题的开始。

标签: mysql sql foreign-keys mariadb


【解决方案1】:

为什么不引用主键?这确实是主键的用途。

如果你真的,真的需要使用不同的键,那么你应该在它上面定义一个唯一的索引:

create unique index unq_rx_r_hash on rx(r_hash);

【讨论】:

  • 让我问你这个问题:rx 上的主键将只是一个自动递增的 int.. 那么数据库会知道在 r_c_hash 和 r_id 之间建立连接吗?
  • @user2879041 。 . .不,当您在 cx 中插入一行时,您将输入适当的 r_id 值作为参考。
  • 好的,所以我认为这是真正的问题。我在同一时间插入这些表。我认为我需要重新考虑 rx 表结构
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2011-02-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多