Vu Database SQL: DML ,DDL and DCL

SQL: DML ,DDL and DCL

  1. 数据操纵语言(DML: Data Manipulation Language)
    主要用来对数据库的数据进行一些操作,常用的就是INSERT、UPDATE、DELETE。
    语法:

    INSERT INTO <表名>(列1,列2,…) VALUES (值1,值2,…);

    UPDATE <表名> SET <列名>=新值 WHERE <列名>=某值;

    DELETE FROM <表名> WHERE <列名>=某值;

  2. 数据定义语言(DDL: Data Definition Language)
    常用的有CREATE、DROP、ALTER,用于在数据库中创建新表或删除表,以及用来创建数据库中的各种对象-----表、视图、索引、同义词、聚簇等。
    语法:
    <1>创建表
    形如:
    create table CSDN (
    csdnid varchar (10) not null ,
    csdnname varchar (20) not null ,
    studentID varchar (20) not null ,
    primary key (csdnid) );
    <2>设置PK并连接
    形如:
    alter table csdn add constraint fk foreign key (studentid)
    references student (studentid);
    <3>表中增添某一列
    形如:
    alter table csdn
    add topic varchar (45);
    <4>表中删减某一列
    形如:
    alter table csdn
    drop topic ;
    <5>删除一整个表
    drop table csdn;

  3. 数据库控制语言(DCL: Data Control Language)
    数据控制语言DCL用来授予或回收访问数据库的某种特权,并控制
    数据库操纵事务发生的时间及效果,对数据库实行监视等。
    (这个东西老师基本没咋讲,应该不考。哈哈哈)

DML 例 1 :

我们先建一个空表,任何用insert语句插入信息
1

insert into student 
values ( "s777777" , "whh" , "[email protected]" , "7777" , "nearby school" , "2000-02-04" );

运行结果:
2
也可以一次插入多行,如下:

insert into student 
values ( "s777778" , "whh" , "[email protected]" , "7777" , "nearby school" , "2000-02-04" ),
( "s777779" , "whh" , "[email protected]" , "7777" , "nearby school" , "2000-02-04" );

运行结果:
3

DML 例 2 :

update student 
set phone = "1111"
where studentid = "s777777";

运行结果:
4
DML 例 3 :

delete from student 
where studentid = "s777777" ;

运行结果:
5

DDL 例 1:

create table CSDN (
csdnid varchar (10) not null ,
csdnname varchar (20) not null , 
studentID varchar (20) not null , 
primary key (csdnid) );

运行结果:
6
DDL 例 2:

在一个表中设立一个FK并将其与其他表的PK关联。

alter table csdn add constraint fk foreign key (studentid) 
references student (studentid);

DDL 例 3:

增加表中的某一列

alter table csdn
add topic varchar (45);

运行结果:
7
DDL 例 4:

删除表中的某一列

alter table csdn
drop topic ;

运行结果:
8
DDL 例 5:

删除一整个表

drop table csdn;

运行结果:
9

DDL 例 6:

我们来创建view(视图)。

  • 什么是view?

视图(view)是一种虚拟存在的表,是一个逻辑表,本身并不包含数据。作为一个select语句保存在数据字典中的。

  • 为什么要使用视图?因为视图的诸多优点,如下:

1)简单:使用视图的用户完全不需要关心后面对应的表的结构、关联条件和筛选条件,对用户来说已经是过滤好的复合条件的结果集。
2)安全:使用视图的用户只能访问他们被允许查询的结果集,对表的权限管理并不能限制到某个行某个列,但是通过视图就可以简单的实现。
3)数据独立:一旦视图的结构确定了,可以屏蔽表结构变化对用户的影响,源表增加列对视图没有影响;源表修改列名,则可以通过修改视图来解决,不会造成对访问者的影响。
总而言之,使用视图的大部分情况是为了保障数据安全性,提高查询效率。

在创建view前先set as default schema(设置为默认架构),这是为了让view可以找到表里的数据。

10
之后再点create view
11

CREATE VIEW `csdn` AS
select customerNumber , city , country
from customers
where country = "USA";

运行结果:
12
大家应该发现了,就多第一句CREATE VIEW ‘view名’ AS,之后的SQL语句就是我们之前讲的单表查询和多表查询,这里就不再多写例题了。

想删除view的话也很简单,和之前删除表操作类似,如下:

drop view csdn;
发布了54 篇原创文章 · 获赞 27 · 访问量 2684

猜你喜欢

转载自blog.csdn.net/Deam_swan_goose/article/details/103328649