zoukankan      html  css  js  c++  java
  • 多对多

    多对多

    # 多对多:一定要创建第三张表(关系表),每一个外键值不唯一,看可以多个外键建立联合唯一
    
    mysql>: drop table author;
    mysql>: drop table author_detail;
    mysql>: drop table book;
    mysql>: drop table publish;
    
    # 作者(author):id, name, age
    create table author(
    	id int primary key auto_increment,
        name varchar(64),
        age int unsigned default 0
    );
    
    # 出版社(publish):id, name, address
    create table publish(
    	id int primary key auto_increment,
        name varchar(64),
        address varchar(256)
    );
    
    # 作者与出版社关系表:id, author_id, publish_id
    create table author_publish(
    	id int primary key auto_increment,
        # 关系表一定有多个外键,关联着多张表
        # 关联作者表
        author_id int,
        foreign key(author_id) references author(id)
        on update cascade
        on delete cascade,
        # 关联出版社表
        publish_id int,
        foreign key(publish_id) references publish(id)
        on update cascade
        on delete cascade,
        # 建立两个字段的联合唯一
        unique(author_id, publish_id)
    );
    
    # 注:关系表 关联着 作者 和 出版社 两张表,在表结构上 作者 与 出版社 两表键没有任何关系
    
    
    # 增:两张被关联表,没有前后关系,但关系表必须在两个表都提供数据后才能进行 关系匹配
    mysql>: insert into author(name, age) values('ruakei', 67),('engo', 76),('Lxx', 3);
    mysql>: insert into publish(name, address) values('老男孩出版社', '上海'),('小女孩出版社', '北京');
    
    # 操作关系表:
    mysql>: insert into author_publish(author_id, publish_id) values(1,1),(1,2),(2,1),(2,2),(3,1);
    
    # 关系表操作:增、删、改,只要两张被关系表有提供对应的操作数据,都可以操作成功,且对两张被关系表没有影响
    
    
    # 操作两张被关系表:
    #		增:不会影响关系表
    mysql>: insert into publish(name, address) values('西交大出版社', '西安');
    #		改:关系表都会级联更新
    mysql>: update publish set id=10 where id=1;
    #		删:关系表都会级联删除
    mysql>: delete from author where name='ruakei';
    
  • 相关阅读:
    ios 封装sqllite3接口
    ios7与ios6UI风格区别
    C/C++面试题
    单链表反转
    字符串倒序输出
    简单选择排序
    插入排序
    冒泡
    快速排序
    C++ new delete(二)
  • 原文地址:https://www.cnblogs.com/aden668/p/11580194.html
Copyright © 2011-2022 走看看