我可以写一个表,级联删除引用这个表的记录。就是用on  delete cascade,
也可以写一个级联更新,就是用on update cascade,
但我如何让这两个同时都设置呢?
我在建立一个表的时候,怎么同时写这两个呢?要在同一个字段啊。 

解决方案 »

  1.   

    直接加上就行了啊?你现在的 create table 语句是什么?
      

  2.   

    mysql> insert into a values (1),(2),(3);
    Query OK, 3 rows affected (0.02 sec)
    Records: 3  Duplicates: 0  Warnings: 0-- ON DELETE CASCADE ON UPDATE CASCADE // ACMAIN 按照这个写法就行了。
    mysql> create table b (
        ->  bid int primary key,
        ->  aid int,
        ->  FOREIGN KEY (aid) REFERENCES a (aid)
        ->          ON DELETE CASCADE ON UPDATE CASCADE
        -> ) engine=innodb;
    Query OK, 0 rows affected (0.06 sec)mysql> insert into b values
        -> (1,1),
        -> (2,1),
        -> (3,2);
    Query OK, 3 rows affected (0.05 sec)
    Records: 3  Duplicates: 0  Warnings: 0mysql> select * from a;
    +-----+
    | aid |
    +-----+
    |   1 |
    |   2 |
    |   3 |
    +-----+
    3 rows in set (0.00 sec)mysql> select * from b;
    +-----+------+
    | bid | aid  |
    +-----+------+
    |   1 |    1 |
    |   2 |    1 |
    |   3 |    2 |
    +-----+------+
    3 rows in set (0.00 sec) -- 测试 update
    mysql> update a set aid=10 where aid=1;
    Query OK, 1 row affected (0.08 sec)
    Rows matched: 1  Changed: 1  Warnings: 0mysql> select * from a;
    +-----+
    | aid |
    +-----+
    |   2 |
    |   3 |
    |  10 |
    +-----+
    3 rows in set (0.00 sec)mysql> select * from b;
    +-----+------+
    | bid | aid  |
    +-----+------+
    |   3 |    2 |
    |   1 |   10 |
    |   2 |   10 |
    +-----+------+
    3 rows in set (0.00 sec)-- 测试 delete
    mysql> delete from a where aid=10;
    Query OK, 1 row affected (0.05 sec)mysql> select * from a;
    +-----+
    | aid |
    +-----+
    |   2 |
    |   3 |
    +-----+
    2 rows in set (0.00 sec)mysql> select * from b;
    +-----+------+
    | bid | aid  |
    +-----+------+
    |   3 |    2 |
    +-----+------+
    1 row in set (0.00 sec)mysql>
      

  3.   

    create table t_a (id int(5) not null auto_increment primary key,t_n varchar(20));
    create table t_b (id int(5) not null,ta_id int(5),t_n varchar(20)
     foreign key (ta_id) references t_a(id) on delete cascade
    );现在想把级联更新也加上。
      

  4.   

     上面不是已经给你例子了吗?create table t_a (id int(5) not null auto_increment primary key,t_n varchar(20));
    create table t_b (id int(5) not null,ta_id int(5),t_n varchar(20)
     foreign key (ta_id) references t_a(id) on delete cascade ON UPDATE CASCADE
    );
      

  5.   

    谢谢,我试验过了,成功!
    原来我是这样写的on delete update cascade.所以错了。多谢。