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 表名;

最新文章

  1. 关于WCF报错之调用方未由服务器进行身份验证
  2. 如何给不支持新特性的浏览器打补丁(让老版本IE兼容新特性)
  3. java 面试每日一题7
  4. C语言中的fread和fwrite
  5. sql每五秒插入一条数据 一次插入N条数据
  6. 【和我一起学习Unity3D】Unity3D的坐标控制
  7. iOS-xcode代码统计
  8. Web开发笔记
  9. ORACLE数据库维护
  10. C#中文件下载的几种方法演示源码
  11. cordova + Vue 开发 APP 上手指南
  12. httpclient 请求 json 数据
  13. Scikit-Learn实战KNN
  14. SQL语句执行过程详解
  15. 【LeetCode3】Longest Substring Without Repeating Characters★★
  16. p4factory下 targets/basic_rout
  17. Linux下文件特殊权限
  18. 基于jquery仿360网站图片选项卡切换代码
  19. 【Error】SSL InsecurePlatform error when using Requests package
  20. MySQL中大数字加减,不产生千位符和科学计数

热门文章

  1. TCP连接复用
  2. Luogu P3258 松鼠的新家(树链剖分+线段树/树状数组)
  3. POJ 2484 A Funny Game 博弈论 对称博弈
  4. HDU 2255 奔小康赚大钱(KM算法)
  5. BZOJ 1834 [ZJOI2010]network 网络扩容(费用流)
  6. [LOJ2553]暴力写挂
  7. [HDU4729]An Easy Problem for Elfness
  8. [POJ3728]The merchant
  9. (原创)Stanford Machine Learning (by Andrew NG) --- (week 3) Logistic Regression & Regularization
  10. Problem A: 自定义函数strcomp(),实现两个字符串的比较