I have the following scenario: A 'phone' child table can serve several parent tables through join tables, as follows:
CREATE TABLE phone (
id BIGINT AUTO_INCREMENT,
number VARCHAR(16) NOT NULL,
type VARCHAR(16) NOT NULL,
PRIMARY KEY(id)
);
CREATE TABLE employee_phone (
id BIGINT AUTO_INCREMENT,
employee BIGINT NOT NULL,
phone BIGINT NOT NULL,
PRIMARY KEY(id),
CONSTRAINT empl_phone_u_phone UNIQUE(phone),
CONSTRAINT empl_phone_fk_employee
FOREIGN KEY(employee)
REFERENCES employee(id) ON DELETE CASCADE,
CONSTRAINT empl_phone_fk_phone
FOREIGN KEY(phone)
REFERENCES phone(id) ON DELETE CASCADE
);
Let Alice and Bob live in the same house and be employees of the same company. HR has two phone numbers registered for Alice whereas they have only one for Bob, the number of the house's landline. Is there a way to enforce at database level that a phone number (number-type) cannot be repeated for the same employee (or supplier, or whatever parent appears later), using this configuration? Or will I have to take care of such restrictions in the application layer? I'd rather not use triggers or table denormalization (as seen in related questions on the site such as this one, which work with IDs, not with other fields), but I'm open to do so if there's no alternative. I'm using MySQL. Thanks for your attention.