常用数据库命令

目录

1、DDL(数据定义语言)

2、DML(数据操作语言)

3、DCL(数据库控制语言)



注:

[ ]  ——这里内容按需选填

<> ——这里内容必填

1、DDL(数据定义语言)

①创建数据库

create database database_name

例:创建“TEST”数据库

create database TEST

 ②创建新表

creat table name (col1 type, [col2,type] [……])

 例:创建“student”表

create table student(sname char(10), sage smallint,sno int)

③删除表

drop table tablename

例:删除“student”表

drop table student

 ④在创建表时,设置主键、约束条件等

creat table name (col1 type 条件, [col2 type 条件,] [col3 type……])

例:创建student表并添加限定条件

create table student
(sname char(10) unique,--unqiue约束
sage smallint,
sno int primary key)--主码

 ⑤修改基本表

alter table <name>

[add [col] <name> <type> [约束] ]    //添加新列

[add 约束条件(col) ]        //添加约束条件

[drop [col] <name> [cascade或restrict] ]        //cascade:自动删除引用该列的其他对象;

                                                               //restrict:如果被引用,为了数据库安全性,禁止该操作

[drop constraint <约束>  [cascade或restrict] ]        //删除完整性约束

[alter col <name> <type> ]        //修改列,包括名、类型等

例:新加列”phone”,和“error”,类型为int,然后修改列”phone“类型为char,删除列error

alter table student
--add phone int
--add error int
--alter column phone char(20)
--drop column error
add unique (phone)--phone必须取唯一值

 ⑥删除数据库、表

drop database/table name

……

2、DML(数据操作语言)

①select 查

select [all/distinct] <表达式1>[,表达式2][……]                //默认为ALL,distinct:去掉重复值

from <表或视图>[,<表或视图>]……(select……) 

        [AS]<别名>

[Where <条件>]        //添加相应操作,可完成连接查询、嵌套查询

[Group by< 列> [having <条件>] ]        //使用group by分组后就不能使用where作为筛选条件

[ order by <列>  [ASC/DESC] ]        //默认为升序:ASC,DESC为降序

例:查询销售订单表中各种商品的订货总数,输出字段为商品编号,订货总数,按照订货总数降序排列。

select ProductID 商品编号, SUM(SellOrderNumber) 订货总数
from Sell_Order
group by ProductID
order by SUM(SellOrderNumber) desc

 sell-order结构如下:

执行结果如下:

②insert 插入

insert

into <tablename> [<col1> <col2>……]        //当插入是一个完整的元组并且与表中定义顺序一致时可不写列名,写列名可不按定义的表的顺序来

[values(’ ‘,’ ‘, ’ ‘……) ]        //要与into语句的顺序一致

[where ……]

例:在student表中插入“wang”的信息

insert
into student
values ('wang','20','123','19852038119')

 查询验证

select *
from student
where sage='20'

 

 插入“li”的部分信息并验证

 ③update修改

update <tablename>

set <col1>= <表达式1> [<col2>= <表达式2>……]

[where <条件> ]        //可以使用嵌套循环等

例:修改“li”的年龄为23

④delete删除

delete        //注意区分drop,这部分删除的数据,而drop删除的是表的结构

from <tablename>

[where <条件> ]        //可以使用嵌套循环等

 例:删除学号为123的学生信息

delete
from student
where sno=123
select *
from student

3、DCL(数据库控制语言)

①grant授权

grant <权限>[,<权限>……]

on <对象类型,如table,view等><name>[,<对象类型><name>……]

to<用户1>[,<用户2>……]          //可以用public,意为全体用户      

[with grant option];        //可以再授权(可以再转给其他人)

例:把查询student表的权限受给用户u3/所有用户,并允许他再将此授权给其他用户

grant select
on table student
to u3
--to public
with grant option

②rewoke 收回权限

revoke <权限>[,<权限>……]

on <对象类型,如table,view等><name>[,<对象类型><name>……]

from <用户1>[,<用户2>……] [cascade/restrict]        //限定条件与前面叙述的一致

例:收回用户u3/所有用户查询student表的权限

revoke select
on table student
from u3
--from public

……


版权声明:本文为qq_56466142原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。