复习四——sql语句

操作

创建基本表

Create Table Student(
    S# Varchar2(10) Constraint PK Primary Key,
    Sname Varchar2(20) NOT NULL,
    Age Number(3),
    Sex Char(1) Default 'F'
)

(我发现这个代码框创建完成之后,再插入一些代码,它就不会对这些新加的代码做应有的高亮了。好菜啊,这个什么TinyMCE编辑器)。

我不知道列名S#是不是合法的,反正ppt上这么写,大概可能只是类似伪代码这样子吧,告诉你大概是这么操作,但是名称合不合法就不一定了。

列约束和表约束举例

Create Table Student(
    S# Varchar2(10) Constraint PK_S Primary Key,
    Sname Varchar2(20),
    Age Number(3) Constraint CK_S Check (age>14 and age<100),
    Sex Char(1),
    Constraint UQ_S Unique(Sname),
    Constraint CK_SS Check (Sex IN (‘M’,’F’))
)

Unique约束:不能重复,但可以为空。若约束列中有一列不为空,就实施约束;若约束列都为空,则不实施约束。

修改基本表

Alter Table 表名
    [Add <列定义>] |
    [Modify <列定义>] |
    [Rename Colume <old> To <new>] |
    [Drop Column <列名>] |
    [Add <表约束>] |
    [Drop Constraint <约束名>] |
    [Rename To <new_table_name>]

插入记录

Insert into <表名> (列名1,列名2,...,列名n)Values(值1,值2,...,值n)

修改记录

Update <表名> Set <列名1>=<值1>,<列名2>=<值2>,...,<列名n>=<值n> where 条件

删除记录

delete from <表名> where <条件>

查询记录

Select 列名表
    from 表名列表
    where 条件
    group by 分组列名表
        having 条件
    order by 排序列名表

使用别名

Select s# AS 学号,sname AS 姓名 From Student

其他

 1 select * from student where s# in ('s001','s003','s006','s008');
 2 
 3 select * from student where age is null;
 4 
 5 select * from student where sname like 'R%S_';
 6 
 7 select * from student where age is null and sname like 'R%';
 8 
 9 select distinct sname,age from student;
10 
11 select * from student order by age asc,sname desc;
12 
13 select count(*) from student;
14 
15 select count(distinct s#) from sc;
16 
17 select acg(age) as average_age from student;
18 
19 select age,count(*) as students from student group by age having count(*)>5;
20 
21 select student.s#,student.sname,sc.c# from student,sc where student.s# = sc.s#
22 
23 select s#,sname from student where s# not in(select distinct s# from sc);
24 
25 select s#,sname from student where exists(select * from sc where sc.s#=student.s#);

创建视图

create view 视图名 (列名1,列名2,...,列名n) as 查询 [with read only]

不是所有的视图都是可更新的:

  • 基于联接查询的视图不可更新
  • 使用了函数、表达式、Distinct的视图不可更新
  • 使用了分组聚集操作的视图不可更新

猜你喜欢

转载自www.cnblogs.com/terieqin/p/9211130.html