Question

My table is as follows:

CREATE TABLE IF NOT EXISTS PHONES (
    number VARCHAR(10),
    id INT,
    type VARCHAR(10),
    PRIMARY KEY (number),
    FOREIGN KEY (id)
        REFERENCES TECHNICIANS(id)
        ON DELETE CASCADE
) ENGINE = INNODB;

I would like to specify for each id one primary contact number. I was thinking of adding a boolean column, but I can't figure out how to get it to only allow one "true" value per. id.

Was it helpful?

Solution

You've basically got 3 options...

  1. have a boolean column but it's up to your application to maintain it
  2. have an integer so you store priority (0=prime, 1=secondary, 2=tertiary,...) again you'll have to maintain it
  3. Have a parent-child relationship so a parent (technician?) record has multiple child (phone number) records. The parent record would then also contain the Id of the primary child record. The only down-side is that adding records either becomes multi-step (add technician, add phone numbers, set primary phone number for technician) or you'll need a smart DAL which does it for you :)

Incidentally, I'm assuming you actually mean one primary number per TechnicianId not per PhoneId

OTHER TIPS

I'd add a foreign key from TECHNICIANS back to PHONES:

ALTER TABLE TECHNICIANS
  ADD COLUMN primary_number VARCHAR(10),
  ADD CONSTRAINT FOREIGN KEY (primary_number) REFERENCES PHONES (number)
    ON UPDATE CASCADE
    ON DELETE SET NULL;

This creates a cyclical reference: technicians references phones, and phones references technicians. This is okay, but it requires special handling when you do things like dropping tables, restoring backups, etc.

Use a "loophole" in MySQL. The MySQL documentation says:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

This means that you can create a boolean column that has two values: true (or 1) and NULL. Create a UNIQUE index over that column + your key. That allows you to only set one record to true, but any number of them can have NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top