日期:2014-05-16 浏览次数:20860 次
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>