• MySQL外键及级联删除 && 表的存储引擎与创建索引 && 删除数据库和表


    Messages表:

    mysql>create table Messages(

           ->message_id int auto_increment primary key, 

           ->user_name varchar(50) not null,

           ->author_id int not null,

           ->body text,

           ->forum_id int not null);

    Forums表:

    mysql>create table Forums(

            ->forum_id int auto_increment primary key,

            ->name varchar(150),

            ->description text,

            ->owner_id int);

    两种最常见的引擎是MyISAM和InnDB。(MyIsAm更快并且表存储所需空间更少,,InnoDB 支持SQL事务处理所需的更加健壮的表和记录锁定);

    在SQL中使用create table 语句时可以指定存储引擎:

    mysql>create table Messages(

           ->message_id int auto_increment primary key, 

           ->user_name varchar(50) not null,

           ->author_id int not null,

           ->body text,

           ->forum_id int not null

           ->)engine InnoDB;

    对于某个表,比如Messages表,我们常常希望有效的搜索这个表,在只给定用户名(user_name)的条件下查找记录。

    我们可以通过把索引添加到create table语句中完成这一操作:

    mysql>create table Messages(

           ->message_id int auto_increment primary key, 

           ->user_name varchar(50) not null,

           ->author_id int not null,

           ->body text,

           ->forum_id int not null

           ->index(user_name)

           ->)engine InnoDB;

    如果我们后来又发现需要频繁的搜索author_id字段,那么使用create index 语句 我们可以在创建表之后创建索引:

    create index author_id on Messages (author_id);

    外键和级联删除::::

    前面的连个表中,我们发现用于消息的表具有引用forums表的外键,:forums_id int not null

     这表示我们希望messages中的forums_id只能是来自forums表中的forums_id 的合法标示符,虽然可以在用户添加消息时候添加一下代码验证forums_id是合法的,但是我们可以让数据库服务器通过强制外键来替我们完成这个工作,:

    foreign key (formus_id) references Forums (forums_id);   

    如果试图把forums_id字段添加不表示来自适当表的合法标示符到Messages表,就会导致错误。

    当我们想删除一个表时例如Forums 就会导致Messages表中有一行指向不在的Forums表,我们在设计Web应用程序时候,希望数据库自动删除所有属于这个表的消息,那么可以进一步修改foreign key约束,让他执行级联删除。当父表(Forums)中的记录被删除时候,子表(Messages)中外键引用的的被设置为刚被删除的父记录的Id(例如forums_id)的任何记录也被数据库引擎删除。

    通过在外键声明中添加on delete cascade :

    foreign key (forums_id) references Forums (forum_id)

       on delete cascade

    删除数据库和表:

    在SQL中,使用drop database和drop table 查询执行这些任务。这两个查询都使用要删除的实体的名称作为参数:

    drop database 数据库名;

    drop table 表名;

  • 相关阅读:
    比特币全节点(bitcoind) eth 全节点
    Knowledge Tracing -- 基于贝叶斯的学生知识点追踪(BKT)
    trate
    spark
    linux 切换c++版本
    查找两个数组的相同字符(两个超大文件的相同字符)
    作业调度框架FluentScheduler
    .net与js数据交换中文乱码问题解决
    数据库死锁问题
    Service Fabric service 根据环境变量读取配置文件
  • 原文地址:https://www.cnblogs.com/perseverancevictory/p/4226473.html
Copyright © 2020-2023  润新知