简体   繁体   中英

Create Foreign key from a primary key

I'm using MySQL & I need to create following tables.

1st table : having 3 attributes A,B,C 
2nd table : having 2 attributes B,D
3rd table : having 2 attributes C,E

Now, A is the primary key.

I need to create the 2nd-3rd tables, such that the values in B for 2nd table should be already present in 1st table's B attribute, & similarly values in C of 3rd table should be already present in C of 1st table.

My attempts :

1) put A in both, 2nd & 3rd tables, & keep them as foreign key referencing A of 1st table, & put on update cascade in each.

2) keep check constraints for both 2nd & 3rd tables, although I couldnt find proper syntax for the check constraints when attributes are from different tables.

Pl suggest better options or improvise the current approaches I've thought of.

such that the values in B for 2nd table should be already present in 1st table's B attribute , & similarly values in C of 3rd table should be already present in C of 1st table.

In order to satisfy the first requirement, B must be declared as unique in the first table. To satisfy the second requirement, C must be unique in the first table. Thus, we would get a structure of (the choice of data type is arbitrary):

Create Table FirstTable
    (
    A varchar(50) not null Primary Key
    , B varchar(50) Unique
    , C varchar(50) Unique
    );

Create Table SecondTable
    (
    B varchar(50)
    , D varchar(50)
    );

Alter Table SecondTable
  Add Constraint FK_SecondTable_FirstTable_B
  Foreign Key ( B )
  References FirstTable ( B )
  On Update Cascade;

Create Table ThirdTable
    (
    C varchar(50)
    , E varchar(50)
    );

Alter Table ThirdTable
  Add Constraint FK_ThirdTable_FirstTable_C
  Foreign Key ( C )
  References FirstTable ( C )
  On Update Cascade;

With respect to check constraints, one of the "cute" features of MySQL is that while it parses and accepts a check constraint in the Create Table statement, it completely ignores them with respect to evalution. To wit:

The CHECK clause is parsed but ignored by all storage engines.

Create Table documentation

Now, even if that were not the case, the Check constraint mechanism in the SQL language can only reference columns in the current table and thus would not help to solve your problem.

I'm not sure I fully understand the question. Would it not be sensible to have attributes B and C as Primary keys to Table 2, and 3 respectively. You could then reference them as foreign keys in the 1st table.

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