mysql - 我怎样才能处理这个一对多的关系,这个约束在一个 note ON 字段上?

标签 mysql sql database foreign-keys rdbms

我不是很喜欢数据库,但我遇到了以下问题。我正在使用 MySQL

我有如下两个表:

1) transfers 表:

CREATE TABLE transfers (
  id           BigInt NOT NULL AUTO_INCREMENT,
  processed    Char(1) NOT NULL,
  providerpid  VarChar(16) NOT NULL,
  recipientpid VarChar(16) NOT NULL,
  symbol       VarChar(128) NOT NULL,
  `type`       VarChar(4) NOT NULL, 
  PRIMARY KEY (
      id
  )
) ;
ALTER TABLE transfers COMMENT = '';

2) 附件1表:

CREATE TABLE annex1 (
  id     BigInt NOT NULL AUTO_INCREMENT,
  symbol VarChar(128) NOT NULL,
  doi    VarChar(256), 
  PRIMARY KEY (
      id
  )
) ;
ALTER TABLE annex1 COMMENT = '';

我收到了以下对我来说很奇怪的要求(但也许我遗漏了什么):

The annex1.symbol values have to be a value have to be a foreign key references transfers.symbol.

据我所知,这应该是因为我必须对这两个表使用 JOIN 来获取与 transfers 记录相关的所有 annex1 记录(它是一对多关系)。

但我无法将其创建为 annex1.symbol 上的 FK 约束,因为 transfers.symbol 不是 PK。

我错过了什么吗?我能否以某种方式指定 annex1.symbol 必须包含 transfers.symbol 的可能值?

最佳答案

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

不需要完全 PK,但您需要在 transfers.symbol 列上建立索引,以添加 FOREIGN KEY,例如:

create index ix on transfers(symbol); -- If this column have (and WILL IN FUTURE ALSO) unique values only, you can define this as UNIQUE index.

ALTER TABLE annex1 ADD CONSTRAINT fk FOREIGN KEY (symbol) REFERENCES transfers(symbol);

关于mysql - 我怎样才能处理这个一对多的关系,这个约束在一个 note ON 字段上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199136/

相关文章:

c# - 获取日期值并将其存储在 MySQL 数据库中?

mysql - 根据另一个表选择数据

sql - 甲骨文 SQL : Why is my function outputting null?

mysql - 数据库中的数据太多 - 需要做出 "replication"决策

c# - 在 C# 中使用 UPDATE MySQL 命令

MySQL:LOAD DATA INFILE csv 忽略主字段插入

mysql - 从多个表中获取不同的结果

sql - Oracle SQL - REGEXP_LIKE 包含 a-z 或 A-Z 以外的字符

ruby-on-rails - 在 Rails 3.2 的数据库中实现数据更新时出错

php - CakePHP数据库设计: associations for job board