我建議刪除'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