方案一:
主表A,从表B;
create table A(id int not null primary key) engine = innodb;
create table B(id int not null,foreign key(id) references A(id) on update cascade on delete cascade)engine = innodb;以上就是一个简单的外键约束关系。在我们执行 delete from A where id = XXX; 时 B表中的相应的数据也被删除。方案二:
表A,表B
create table A(id int not null primary key) engine = innodb;
create table B(id int not null primary key)engine = innodb;没有外键约束关系
所以我们需要执行delete from A where id = XXX; delete from B where id = XXX;
请问以上两种方案 效率差在哪里?也就是外键是如何提高效率的。

解决方案 »

  1.   

    便利性和性能往往不能两全。还在学习期间,所以原理性也说不清,可以去看下InnoDB相关的资料。
      

  2.   

    使用外键是需要代价的:即时检查,逐行进行
    每次修改时都要对另外一张表多一次select操作,使用select lock in share mode方式
    这将导致更多的锁等待,甚至是死锁,因为关联到其他表,死锁很难被爬出
    虽然没有具体的性能测试报告,但外键约束往往是应用性能瓶颈所在
    比如,我们现在的线上环境就没有外键的存在