Domanda

I have the following table setup:

CREATE TABLE IF NOT EXISTS `appointment` (
  `idappointment` int(11) NOT NULL AUTO_INCREMENT,
  `appdate` datetime NOT NULL,
  `appnote` varchar(255) DEFAULT 'Please enter a relevant note',
  `chair_idchair` int(11) NOT NULL,
  PRIMARY KEY (`idappointment`,`chair_idchair`),
  KEY `fk_appointment_chair_idx` (`chair_idchair`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;

Typical values for the appdate field are: 2013-07-05 08:30:00 and 2013-07-05 09:00:00 so no timestamp values and all appointments differ with a fixed time interval.

For my application I need to ensure that no single chair is double booked at the same time interval, for this reason I thought of creating a composite primary key consisting of the appdate field and the chair_idchair field and then setting this composite primary key to unique.

My question is how would one do this in MySQL and more importantly is it actually the best way to ensure that no double bookings can be booked from the DB's side. I don't want to just rely on the app to do this checking as users will be booking from multiple locations concurrently.

È stato utile?

Soluzione

Making a composite primary key containing appdate and chair_idchair will not solve the problem. If appdate for one entry if 2013-07-05 08:30:00 then it will allow another entry with appdate 2013-07-05 08:31:00 for the same chair id, which is incorrect.

To overcome this, before inserting any entry, you will need to check if there is any appointment whose time is overlapping with the current appointment by a query and then only you should allow insert.

E.g. if the duration of an appointment is 30 mins then, before inserting any appointment, you will have to check whether there is any appointment for the same chair whose time is less than 30 mins of the new appointment time.

TIMEDIFF() function of mysql may help you in this.

Altri suggerimenti

As Darshan noted, a composite index like this will not enforce uniqueness on appdate. You would be better off using the autoincrement column for a PK. And add another index on appdate (unique if necessary).

This way it will be as easy to implement, and when your customer decides that you will need to have 2 records with the same appdate in the database it will be easier to change too.

If you want to enforce appdate uniqueness via the database you can create a before insert/update trigger to normalize the value of appdate (for example - converting it from 2013-07-05 12:33:41' to2013-07-05 12:30:00`). And then put a unique constraint with the index.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top