本文共 2614 字,大约阅读时间需要 8 分钟。
SQL(结构化查询语言)是一种标准化的数据库查询语言,广泛应用于多种关系数据库系统中。其功能涵盖数据操纵、数据定义、事务管理、完整性约束以及数据访问控制等多个方面。本文将深入探讨SQL的基本结构、查询方法及其常用操作。
SQL语言分为以下几个主要部分:
在定义关系数据库时,需要考虑以下要素:
SQL定义了多种基本数据类型,如char
(固定长度字符串)、varchar
(可变长度字符串)、int
(整数)、double precision
(双精度浮点数)等。每种类型均可包含一个空值代表。
在实际操作中,用户常使用create table
语句定义关系结构。例如:
create table department ( dept_name varchar(20), building varchar(15), budget numeric(12, 2), primary key (dept_name));create table student ( ID int, name varchar(50), dept_name varchar(20), tot_cred int, primary key (ID), constraint Check_Course constrain (tot_cred Check value 50));
primary key (A1, A2, ..., Am) // 表示属性A1, A2, ..., Am构成关系的主键
foreign key (A1, A2, ..., Am) references relation_name
not null
SQL查询由select
、from
、where
三部分构成。结果关系基于from子句中的关系在where条件下筛选后的元组,并根据select子句指定的属性输出。
select name from instructor;// 删除重复元组select distinct dept_name from instructor;
select name, course_id from instructor, teaches where instructor.ID = teaches.ID;// 自然连接select name, course_id from instructor natural join teaches;
###笛卡尔积与限制
// 笛卡尔积操作select A1, A2, ..., An from r1, r2, ..., rm;// 限制操作select name, course_id from instructor, teaches where instructor.ID = teaches.ID and dept_name = 'Comp. Sci.';
常用聚集函数包括avg
(平均值)、max
(最大值)、sum
(求和)等。这些函数可用于按组汇总数据。
// 计算某系教师的平均工资select avg(salary) from instructor where dept_name = 'Comp. Sci.';// 统计某系教师人数select count(distinct ID) from teaches where dept_name = 'Comp. Sci.';// 组内统计并应用条件select dept_name, count(instructor.ID) from instructor, teaches where semester = 'Spring' and year = 2010 group by dept_name having count(instructor.ID) >= 2;
// 更新操作update instructor set salary = salary * 1.05 where dept_name = 'Comp. Sci.';// 插入操作(重命名)insert into student values (10211, 'Smith', 'Biology', null);// 动态插入操作insert into instructor select ID, name, dept_name, salary from student where dept_name = 'Music' and tot_cred >= 144;
// 起始事务begin transaction;// 执行多次操作insert into course values('CS-437', 'Database Systems', 'Comp. Sci.', 4);update student set tot_cred = sum(credits) where ID = 10211;// 结束事务commit;// 回滚事务rollback;
通过以上内容,可以看出SQL在数据库管理中扮演着核心角色。理解并掌握这些基本知识,对于数据库开发和维护至关重要。
转载地址:http://pomgz.baihongyu.com/