简体   繁体   中英

How can I handle this one to many relationship with this contraint on a not PK field?

I am not so into databases and I have the following problem. I am using MySQL .

I have 2 tables as follows:

1) transfers table:

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) annex1 table:

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

I received the following requirement that seems pretty strange to me (but maybe I am missing something):

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

So from what I have understood it should be because I have to use JOIN with these 2 tables to obtain all the annex1 records related to a transfers record (it is a one to many relationship).

But I can't create this as a FK constraint on annex1.symbol because the transfers.symbol is not a PK.

Am I missing something? Can I specify in some way that the annex1.symbol must contain a possible value of 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

No necessary exactly PK, but you need index on transfers.symbol column, for adding FOREIGN KEY, something like:

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);

Yes you are correct, you can't define relationship on non-key column but you can define symbol as Primary Key too in transfer table by means of composite primary key like

PRIMARY KEY (id, symbol)

(OR) define symbol as UNIQUE KEY CONSTRAINT and in that case as well you can have FK relationship on that column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM