关系型数据库

什么是关系型数据库

  所谓关系型数据库,是指采用了关系模型来组织数据的数据库。

  简单来说,关系模型指的就是二维表格模型,而一个关系型数据库就是由二维表及其之间的联系组成的一个数据组织。下面列出了关系模型中的常用概念。

关系:可以理解为一张二维表,每个关系都具有一个关系名,就是通常说的表名。

元组:可以理解为二维表中的一行,在数据库中经常被称为记录。

属性:可以理解为二维表中的一列,在数据库中经常被称为字段。

域:属性的取值范围,也就是数据库中某一列的取值限制。

关键字:一组可以唯一标识元组的属性。数据库中常称为主键,由一个或多个列组成。

 

如何新建数据库与表

/*新建一个名为student的数据库--if not exists 为保护语句,如果有student表存在也不会报错*/

create database if not exists student;

 

create table  if not exists student(      /*新建student表*/

id int primary key auto_increment,      /*id为主键,int类型,并且自增长*/

stu_name varchar(20),            /*姓名为varchar类型,大小为20字符*/

stu_age smallInt               /*年龄为smallInt类型*/

)

 

注:

char与varchar的区别:

charchar是定长的,也就是当你输入的字符小于你指定的数目时,char(8),你输入的字符小于8时,它会再后面补空值。当你输入的字符大于指定的数时,它会截取超出的字符 。

varchar长度为 n 个字节的可变长度且非 Unicode 的字符数据。n 必须是一个介于 1 和 8,000 之间的数值。存储大小为输入数据的字节的实际长度,而不是 n 个字节。所输入的数据字符长度可以为零。

 

1、CHAR 。CHAR存储定长数据很方便,CHAR字段上的索引效率级高,比如定义char(10),那么不论你存储的数据是否达到了10个字节,都要占去10个字节的空间。 

 

 2、VARCHAR。存储变长数据,但存储效率没有CHAR高。如果一个字段可能的值是不固定长度的,我们只知道它不可能超过10个字符,把它定义为 VARCHAR(10)是最合算的。VARCHAR类型的实际长度是它的值的实际长度+1。为什么“+1”呢?这一个字节用于保存实际使用了多大的长度。 、

 

/*修改表student的引擎为innodb,默认引擎为myisam*/

alter table student ENGINE=INNODB

 

增:

 /*添加对象--并且赋值*/

insert into student values(null,'张三',21)  /*因为id主键,且自增长,所以不用写,但是需要占位,所以用null表示*/

insert into student(id,stu_name) values(2,'李四') 

 /*添加属性--列*/  

 alter table student add gender int   /*给表student添加gender列*/

删:

 /*删除表的属性--列*/

alter table student drop column gender;  /*删除表的gender那一列*/

/*删除对象*/

delete from student where id=1;  /*删除id为1的那一行*/

delete from student where id between 2 and 4;  /*删除id在2和4之间的行*/

改:

/*修改列*/

alter table student change stu_name stu_name varchar(25)  /*将stu_name的varchar长度改为25*/

update student set stu_age=22 where name='zhangsan';  /*将张三的年龄改为22*/

查:

desc student;  /*查看表student的属性-field,类型type*/

select * from where id=1  /*查看id为1的那一行信息*/

select count(*) from student  /*查看表student有多少行*/

select distinct stu_age from student  /*去重,查看有哪些年龄段*/

select concat(stu_name,"的年龄为",stu_age) from student;  /*拼接,显示在一个格中*/

select * from student limit 0,3  /*从第一条开始显示3行*/

select * from student where stu_age in(21,23)  /*显示年龄为21和23的对象*/

select * from student where stu_age between 21 and 23  /*显示年龄在21至23岁之间的对象*/

模糊搜寻:

通配符:"%"  表示0到多个字符   "_"表示单个字符

select * from student where stu_name like 'ma%';  /*查看名字以‘ma’开头的对象*/--%ma--%ma%

select * from student where stu_name like 'm_'    /*查看m开头,后跟一个字符的名字*/

select stu_name as 姓名 from student as s  /*as +表、列别名 ,并且可通过“表别名.”产生提示,as可以不写*/

select * from student order by age     /*升序排列显示,如果结尾+desc则为降序排列*/

posted @ 2016-05-14 23:33  forevery  阅读(238)  评论(0编辑  收藏  举报