我建议删除'isStandardName'列。创建一个表standard_country。创建了国家和standard_country之间的关系。使用左连接创建视图并更改模型以使用新结构。
例子。
CREATE TABLE `country` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`country` varchar(63) DEFAULT NULL,
`code` char(3) DEFAULT NULL COMMENT 'ISO 3166-1 alpha-3',
PRIMARY KEY (`id`),
UNIQUE KEY `country` (`country`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `country` (`id`, `country`, `code`)
VALUES
(1,'United States','USA'),
(2,'United States of America','USA'),
(3,'Yankees','USA');
CREATE TABLE `standard_country` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`country_id` int(11) unsigned NOT NULL,
`code` char(3) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `key` (`code`),
KEY `country_id` (`country_id`),
CONSTRAINT `standard_country_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `standard_country` (`id`, `country_id`, `code`)
VALUES
(1,2,'USA');
create or replace view countries_view as
select country.id country_id
, country
, country.code
, COALESCE((standard_country.id > 0) , 0) isStandard
from `country`
left join `standard_country`
on country.id = standard_country.country_id
-- example result
select * from countries_view ;
country_id country code isStandard
1 United States USA 0
2 United States of America USA 1
3 Yankees USA 0
如果我们尝试添加'独特(countryCode,isStandardName)'它也不会允许多于一个布尔'false'。所以根据要求,创建'trigger'会很好。 – Meherzad 2013-04-05 10:19:07
也许,而不是'isStandardName',有一个'UNSIGNED INTEGER'组成的'priority'列。然后可以在'(countryCode,priority)'上定义'UNIQUE'约束,并将一些魔术值(例如0)作为“*标准名称*”。 – eggyal 2013-04-05 10:20:36
但是独特的(countryCode,isStandardName)将不起作用,如果我们有三个USA和两个错误!甚至等于10的国家代码的数量可能会有所不同! – FidEliO 2013-04-05 10:22:43