如何使表中的某个域的值唯一?
数据表中某个域,里面的值只能是“true”或者是“false”,同时只能让一条记录是“true”,其他都是“false”
在MySql中是如何做到的,谢谢!
[解决办法]
见如下例子。
mysql> create table ta ( -> discountid int auto_increment primary key , -> `selected` BOOL -> );Query OK, 0 rows affected (0.09 sec)mysql>mysql> delimiter |mysql>mysql> CREATE TRIGGER ta_bi BEFORE INSERT ON ta -> FOR EACH ROW BEGIN -> DECLARE bExist int default 0; -> select count(*) into bExist from ta where selected; -> if bExist>0 and new.selected then -> set new.discountid=1; -> end if; -> END; -> |Query OK, 0 rows affected (0.08 sec)mysql>mysql> delimiter ;mysql> insert into ta values (null,true);Query OK, 1 row affected (0.06 sec)mysql> insert into ta values (null,true);ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'mysql> insert into ta values (null,false);Query OK, 1 row affected (0.06 sec)mysql> insert into ta values (null,false);Query OK, 1 row affected (0.08 sec)mysql> insert into ta values (null,true);ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'mysql> select * from ta;+------------+----------+| discountid | selected |+------------+----------+| 1 | 1 || 2 | 0 || 3 | 0 |+------------+----------+3 rows in set (0.00 sec)mysql>