I'm stumbled on a tricky problem today, I want to restrict the number of appearance of some values of a field, here's my table:
CREATE TABLE `test_table` (
`id` varchar(40) COLLATE utf8_bin NOT NULL,
`create_time` datetime NOT NULL DEFAULT '2010-01-01 00:00:00',
`user_id` varchar(40) COLLATE utf8_bin NOT NULL,
`device_id` varchar(40) COLLATE utf8_bin NOT NULL,
`is_owner` boolean NOT NULL,
`user_nickname` varchar(45) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `un_device` (`device_id`,`is_owner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
For example, we have two users Bob
and Tom
, and one device Echo
, the relationships among user_id
, device_id
and is_owner
are:
- A device ONLY can have one owner, which means only a pair of (device: Echo, is_owner: true) is allowed.
- A device can have multiple users, this is to say that multiple appearance of the pair(device: Echo, is_owner: false) is allowed.
The unique constraint won't help in my case, please help.