如何在mysql加上一个约束
现在有一个表
id         pid
1         1
2          1
3         null
4         2

这里pid只能是id的值或者为空如何在mysql用约束实现   (oracle sqlserver 是比较简单实现的 )

解决方案 »

  1.   

    在标准的
    SQL
    语言中,我们可以在(
    CREATE TABLE a(a int, b int, check(b=a or b=null))
      

  2.   

    如下即可。mysql> create table t_liyihongcug(
        ->  id      int not null primary key,
        ->  pid     int ,
        ->  CONSTRAINT fk_t_liyihongcug_t_liyihongcug FOREIGN KEY (pid) REFERENCES t_liyihongcug (id)
        -> );
    Query OK, 0 rows affected (0.11 sec)mysql> show create table t_liyihongcug;
    +---------------+---------------------------------------------------------------
    | Table         | Create Table
    +---------------+---------------------------------------------------------------
    | t_liyihongcug | CREATE TABLE `t_liyihongcug` (
      `id` int(11) NOT NULL,
      `pid` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `fk_t_liyihongcug_t_liyihongcug` (`pid`),
      CONSTRAINT `fk_t_liyihongcug_t_liyihongcug` FOREIGN KEY (`pid`) REFERENCES `t_
    liyihongcug` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
    +---------------+---------------------------------------------------------------
    1 row in set (0.00 sec)mysql> insert into t_liyihongcug values (1,null);
    Query OK, 1 row affected (0.06 sec)mysql> insert into t_liyihongcug values (2,3);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint f
    ails (`test`.`t_liyihongcug`, CONSTRAINT `fk_t_liyihongcug_t_liyihongcug` FOREIG
    N KEY (`pid`) REFERENCES `t_liyihongcug` (`id`))
    mysql> insert into t_liyihongcug values (2,1);
    Query OK, 1 row affected (0.06 sec)mysql> select * from t_liyihongcug;
    +----+------+
    | id | pid  |
    +----+------+
    |  1 | NULL |
    |  2 |    1 |
    +----+------+
    2 rows in set (0.00 sec)mysql>
      

  3.   

    不行。
    执行上面的sql, 输入如下data
    a   b
    1   null
    2    1
    3    1   是对的 
    但修改的时候 
    a   b
    1   null
    2    1
    3    31
    发现系统居然不报错, 难道只能用触发器??