答案 0 :(得分:21)
答案 1 :(得分:11)
答案 2 :(得分:8)
答案 3 :(得分:2)
答案 4 :(得分:1)
答案 5 :(得分:0)
MySQL不支持检查约束,这是使用触发器的解决方案:
create table if not exists myTable ( id int not null auto_increment primary key, is_default bit not null ) engine=innodb; select 'create trigger tbi_myTable'; drop trigger if exists tbi_myTable; delimiter // create trigger tbi_myTable before insert on myTable for each row begin if (select count(1) from myTable where is_default=true) > 0 && NEW.is_default then -- Signal is only in 5.6 and above use another way to raise an error: if less than 5.6 SIGNAL SQLSTATE '50000' SET MESSAGE_TEXT = 'Cannot insert into myTable only one row with is_default true is allowed!'; end if; END // delimiter ; insert into myTable (is_default) values (false); insert into myTable (is_default) values (true); insert into myTable (is_default) values (false); insert into myTable (is_default) values (false); -- This will generate an error insert into myTable (is_default) values (true); insert into myTable (is_default) values (false); select * from myTable; -- will give /* id is_default 1 false 2 true 3 false 4 false */