数据库系统笔记6-SQL语句基础

数据定义

基本数据类型

  • char(n) 定长度字符串
  • varchar(n) 可变长度字符串
  • int 整数
  • smallint 小整数
  • numeric(p,d) 定点数,精度由用户指定,p位数字,其中d位数字在小数点右边
  • real, double precision 浮点数,双精度浮点数
  • float(n) 精度至少为n的浮点数
1
2
3
4
5
create table department
(dept_name varchar(20),
building varchar(15),
budget numeric(12,2),
primary key(dept_name));

查询的基本结构

1
2
3
4
5
6
7
8
select dept_name from instructor;
select distinct dept_name from instructor; --去除重复
select all dept_name from instructor; --保留重复,默认
select ID,dept_name,salary*12 from instructor; --属性的算术运算
select name from instroctor where dept_name = 'Comp. Sci.' and salary > 7000; --where语句限定满足特定谓词的元组
select name, instroctor.dept_name, building
from instructor, department
where instructor.dept_name = department.dept_name; --多关系查询

自然链接

1
2
3
select name, title
from instructor natural join teachers, course
where teacher.course_id = course.course_id;

更名运算

将长的关系名替换成短的,这样在其他的查询中方便使用

1
2
3
select name as instructor_name, course_id
from instructor, teaches
where instructor.ID = teaches.ID

字符串运算

  • % 匹配任意字符串
  • _ 匹配任意一个字符
  • \ 转移字符

集合运算

并运算

1
2
3
4
(select course_id from section where semester = 'Fall' and year = 2009)
union
(select course_id from section where semester = 'Spring' and year = 2010)
/*union操作自动默认去重,若保留重复使用union all*/

交运算

intersect

差运算

except

聚集函数

  • avg
  • min
  • max
  • sum
  • count

数据库修改

删除

1
2
delete from t
where P;

插入

1
2
insert into course(course_id, title, dept_name, credits)
values('CS-437', 'Database Systems', 'Comp. Sci.', 4)

更新

1
2
3
update  instructor
set salary = salary * 1.05
where salary < (select avg(salary) from instructor);