码迷,mamicode.com
首页 > 数据库 > 详细

数据库MySQL的创建

时间:2017-03-07 23:05:01      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:结构   分享   creat   建表   ase   uid   gen   into   logs   

1个例子:

  1. 创建一个名为school数据库
  2. 创建一个学生信息表:学号ID(主键,自增),姓名,出生年月,系名(外键),班号(外键),宿舍区
  3. 创建一个班级信息表:班号ID(主键,自增),专业名,系名(外键),人数,入学年份
  4. 创建一个系信息表:系名(主键),系号(主键,自增),系办公地点,人数
  5. 创建一个学生会信息表:学会名(主键),成立年份,办公地点,人数

创建表和数据库:


#如果存在数据库School,则删除。否则创建数据库
drop database if exists `School`;
#创建数据库
create database `School`;
use `School`;
#创建一个学校系表:系号(主键,自增),系办公地点,人数
drop table if exists `tb_dept`;
create table `tb_dept`
(
`id` int(11) not null AUTO_INCREMENT PRIMARY key,
`Local` varchar(32) not null,
`Dnum` int(4) not null
);
#创建一个学生班级表:班级id(主键,自增),专业名,系名(外键),人数
drop table if exists `tb_class`;
create table `tb_class`
(
`id` int(11) not null AUTO_INCREMENT primary key ,
`CName` varchar(32) not null,
`CdeptId` int(11) not null ,
`CNum` int(4) not null,
constraint `FK_Stuid` foreign key(`CdeptId`) references `tb_dept`(`id`)
);
#创建一个学生信息表:学生id(自增,主键),姓名,年龄,性别,所属班级id(外键),宿舍区。
drop table if exists `tb_student`;
create table `tb_student`
(
`id` int(11) not null auto_increment primary key,
`SName` varchar(32) not null,
`Age` int default 0,check(`Age`>0 and `Age`<=100),
`gender` boolean default 0,check(`gender`=0 or `gender`=1),
`classId` int(11) not null ,
constraint `FK_Stuid1` foreign key(`classId`) references `tb_class`(`id`)
);

 

语言书写规范问题:

  1. 括号要分行
  2. 最后一行不需要逗号
  3. 外键时FK_Stuid1值需要改变,即不能重复
  4. 先创建不含外键的数据表,在创建含有外键的数据表

查询创建的数据库:

show databases;

查询表结构:

use school;
desc tb_student;

技术分享

增加数据信息:
#在学生姓名之后添加电话字段
use school;
alter table tb_student add `phone` varchar(15) after `SName`;

技术分享

#为表tb_student添加字段classid,并设置为外键。
use school;
alter table tb_student add deptId int(11) not null;
alter table tb_student add constraint `FK_dept_student` foreign key(`deptId`) references tb_dept(`id`);

技术分享

创建数据记录表:
use school;
insert into tb_dept(id,Local,Dnum) values 
(null,cy,1),
(null,qy,1),
(null,zy,1);

use school;
insert into tb_dept(id,Local,Dnum) values
(null,‘cy‘,‘1‘),
(null,‘ry‘,‘2‘),
(null,‘ty‘,‘3‘);

查询数据库:

SELECT Local,Dnum FROM tb_dept ORDER BY Dnum;

 


技术分享



 

数据库MySQL的创建

标签:结构   分享   creat   建表   ase   uid   gen   into   logs   

原文地址:http://www.cnblogs.com/cyaiky/p/6517140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!