当前位置: 移动技术网 > IT编程>数据库>Mysql > 数据库 基本操作

数据库 基本操作

2019年05月06日  | 移动技术网IT编程  | 我要评论

1. 数据定义语句
 - 模式 
   · 创建: create schema
   · 删除: drop schema
 - 表
   · 创建: create table
   · 删除: drop table
   · 修改: alter table
 - 视图
   · 创建: create view
   · 删除: drop view
 - 索引
   · 索引: create index
   · 删除: drop index
   · 修改: alter index

2.模式的定义与删除
 - 模式定义: create schema <模式名> authorization <用户名>; //为用户定义一个xx模式
 
 - 在创建模式时,创建基本表、视图,定义授权
     create schema <模式名> authorization <用户名> [<表定义子句>|<视图定义子句>|<授权定义子句>]
 
 - 删除模式: drop schema <模式名> <casecade|restrict>;
   · <casecade|restrict> 二者必选其一
     casecade:级联 删除模式时,把该模式中的所有数据库对象全部删除
     restrict:限制 如果该模式已定义下属的数据库对象则拒绝删除

3.基本表的定义、删除、修改
 - 定义:create table <表名> (<列名> <数据类型> [列级完整性约束条件] 
                             [,<列名> <数据类型> [列级完整性约束条件] ] 
                             ... [,<表级完整性约束条件>]);

 - 修改基本表 alter table <表名> [add [column] <新列名> <数据类型> [完整性约束]]
                                 [add <表级完整性约束>]
                                 [drop [column] <列名> [casecade|restrict] ]
                                 [drop constraint <完整性约束名> [casecade|restrict] ]
                                 [alter column <列名> <数据类型> ] ;
  · 删除时使用 strict 如果该列被其他对象引用 则拒绝删除该列
  · drop constraint 子句用于删除指定的完整性约束条件 
  · alter column 修改原有的列定义

 - 删除基本表 drop table <表名> [casecade|restrict];

4.索引的建立、修改
 - 建立索引 create [unique] [cluster] index <索引名> on <表名>(<列名> [次序] [,<列名> [次序]]...);
 - 修改索引 alter index <就索引名> rename to <新索引名>
 - 删除索引名 drop index <索引名>;

5. 数据查询
 - 一般格式 select [all | distinct] <目标列表达式> [,<目标列表达式>] ...
            from <表名或视图名> [,<表名或者视图名>...] | (<select语句>) [as] <别名>
            [where <条件表达式>]
            [group by <列名 1> [having <条件表达式>]]
            [order by <列名 2> [asc|desc]]
  · distinct 去掉重复元素
  · order by 排序:asc 升序、 desc 降序 
  · group by 将查询结果按一列或者多列的值分组,值相等的为一组

6. 常用查询条件
 - 确定范围: between and, not between and
 - 确定集合: in, not in
 - 字符匹配: like, not like
   · 通配符 % _ 
     % : 任意长度的字符串 例如:a%b 以a开头b结尾
     _ : 任意字符串 
 - 空值: is null, is not null
 - 逻辑运算: and, or, not

7. 聚集函数
 - 统计元组个数 count(*)
 - 统计列中值个数 count([distinct|all] <列名>)
 - 统计列值总和 sum([distinct|all] <列名>)
 - 平均值 avg([distinct|all] <列名>)
 - 最大值 max([distinct|all] <列名>)
 - 最小值 min([distinct|all] <列名>)

8. 查询例子
- 查询名字中第二个字为阳的学生的名字和学号
  select sname,sno from student where sname like '_阳%'
- 查询计算机科学系年龄在20岁以下的学生姓名
  select sname from student where sdept='cs' and sage<20;
- 查询一号课程学生平均成绩
  select avg(grade) from cs where cno='1';
- 查询平均成绩大于等于90分的学生学号和平均成绩
  select sno,ave(grade) from cs group by sno having avg(grade)>=90;

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网