Problems with MySQL bidirectional relationship and mirrored foreign keys
-
01-07-2021 - |
Question
i have to create two tables with a bidirectional relationship, as in the figure given below. But it always gives an error. I am using the following query for creating the tables.
CREATE TABLE IF NOT EXISTS `rpt_operation` (
`op_id` int(45) NOT NULL,
`component` int(45) NOT NULL,
`ideal_time` time NOT NULL,
`handling_time` time NOT NULL,
PRIMARY KEY (`op_id`),
INDEX (component),
FOREIGN KEY (component)
REFERENCES rpt_component(comp_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `rpt_component` (
`comp_id` int(45) NOT NULL,
`lot_code` int(60) NOT NULL,
`lot_color` varchar(60) NOT NULL,
`drawing_num` int(60) NOT NULL,
`revision_num` int(60) NOT NULL,
`operation` int(45) NOT NULL,
PRIMARY KEY (`comp_id`),
INDEX (operation),
FOREIGN KEY (operation)
REFERENCES rpt_operation(op_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The error appear in the line component int(45) NOT NULL
of rpt_operation table.
Any help will be appreciated.
Thanks in advance
Solution
Your table structure is impossible. You can't insert any records into rpt_operation
because there are no records in rpt_component
for the component
foreign key, and you can't insert any records into rpt_component
because there are no records in rpt_operation
for the operation
foreign key.
If you make one or both of those fields nullable, then the table structure is still recursive, so you have to add one of the foreign keys manually, for example:
ALTER TABLE rpt_operation
ADD CONSTRAINT
FOREIGN KEY (component)
REFERENCES rpt_component(comp_id);
OTHER TIPS
I would suggest you to use a linking-table to resolve this problem. This is not a viable solution and requires workarounds.