I am trying to increase the constraint of my MySQL database schema adding foreign key constraint to each table.
Table 1: USERS
+---------+----------+-------------
| id | username | Other fields
+---------+----------+-------------
| 1 | John |
| 2 | Mark |
+---------+----------+-------------
id
INT(11) UNSIGNED NOT NULL AUTO_INCREMENTusername` VARCHAR(50) NOT NULL
PRIMARY KEY (
id
)
Table 2: DISKS (This has a one to many relationship with USERS)
+---------+----------+-----------+-------------
| id | id_user | disk_name | Other fields
+---------+----------+-----------+-------------
| 1 | 1 | disk A |
| 2 | 2 | disk B |
+---------+----------+-----------+-------------
id
INT(11) UNSIGNED NOT NULL AUTO_INCREMENT
id_user
INT(11) NOT NULL,PRIMARY KEY (
id
,id_user
) INDEXfk_disks_idx
(id
ASC)CONSTRAINT
fk_disks
FOREIGN KEY (
id
)REFERENCES
database
.USERS
(id
)ON DELETE NO ACTION
ON UPDATE NO ACTION)
Table 3: FILES (This has a one to many relationship with DISKS)
+---------+----------+----------+-----------+-------------
| id | id_disk | id_user | file_name | Other fields
+---------+----------+----------+-----------+-------------
| 1 | 1 | 1 | |
| 2 | 2 | 2 | |
+---------+----------+----------+-----------+-------------
id
INT(11) UNSIGNED NOT NULL AUTO_INCREMENT
id_user
INT(11) NOT NULL
id_disk
INT(11) NOT NULLPRIMARY KEY (
id
,id_disk
,id_user
) INDEXfk_files_idx
(id
ASC,id_user
ASC)CONSTRAINT
fk_files
FOREIGN KEY (
id_disk
,id_user
,id_user
)REFERENCES
database
.DISKS
(id
)ON DELETE NO ACTION
ON UPDATE NO ACTION)
Table 2: FILES_ON_NAS (This has a one to one relationship with FILES)
+-------+----------+----------+----------+-----------+-------------
| id | id_files | id_user | id_disk | file_name | Other fields
+-------+----------+----------+----------+-----------+-------------
| 1 | 1 | 1 | 1 | |
| 2 | 1 | 2 | 2 | |
+-------+----------+----------+----------+-----------+-------------
id
INT(11) UNSIGNED NOT NULL AUTO_INCREMENT
id_files
INT(11) NOT NULL,
id_user
INT(11) NOT NULL,
id_disk
INT(11) NOT NULL,PRIMARY KEY (
id
,id_files
,id_user
,id_disk
) INDEXfk_files_on_nas_idx
(id
ASC)CONSTRAINT
fk_files_on_nas
FOREIGN KEY (
id_files
,id_user
,id_disk
)REFERENCES
database
.FILES
(id
,id_user
,id_disk
)ON DELETE NO ACTION
ON UPDATE NO ACTION)
Question:
As you can see the more I reference table in cascade the more primary keys I get. How can I design the database to avoid the replication of primary keys and therefore data duplication as well? Should I delete the auto incremented key for each table? Is it a good practice?
Thanks