关系型语言:SQL与QBE的全面解析
立即解锁
发布时间: 2025-08-13 02:22:21 阅读量: 23 订阅数: 36 


数据库系统原理与实践
### 关系型语言:SQL与QBE的全面解析
在数据库管理中,关系型语言起着至关重要的作用。本文将详细介绍两种常见的关系型语言:SQL(结构化查询语言)和QBE(按例查询),包括它们的查询、更新、函数以及数据定义等方面的内容。
#### 1. SQL语言的使用
SQL是一种广泛使用的数据库语言,它提供了强大的数据操作和数据定义功能。
##### 1.1 SQL查询示例
以下是一些常见的SQL查询示例:
- **查询物理学科且薪资超过19K的导师姓名**:
```sql
SELECT TNAME
FROM TUTOR
WHERE SAL > 19 AND TDN =
(SELECT DNO
FROM DEPT
WHERE DNAME = 'PHYSICS');
```
或者
```sql
SELECT TNAME
FROM TUTOR
WHERE (TDN =
(SELECT DNO
FROM DEPT
WHERE DNAME = 'PHYSICS'))
AND SAL > 19;
```
结果为:
| TNAME |
| --- |
| SMITH |
- **查询薪资超过20K的导师姓名和部门预算**:
```sql
SELECT TNAME, BUDGET
FROM TUTOR, DEPT
WHERE TDN = DNO
AND SAL > 20;
```
结果为:
| TUTOR | BUDGET |
| --- | --- |
| WATT | 600 |
| HARTLY | 400 |
- **查询选修了所有课程C1、C2、C3的学生姓名**:
```sql
SELECT SN
FROM STD, CSL
WHERE S# = SS AND CC = ALL ('C1', 'C2', 'C3');
```
- **查询选修了CRS表中所有课程的学生姓名**:
```sql
SELECT SN
FROM STD, CSL
WHERE S# = SS AND CC = ALL
(SELECT C#
FROM CRS);
```
- **查询没有导师的部门编号**:
```sql
SELECT DNO
FROM DEPT
MINUS
SELECT TDN
FROM TUTOR;
```
结果为:
| DNO |
| --- |
| D22 |
| D30 |
##### 1.2 SQL更新操作
SQL提供了基本的更新命令,用于插入、删除和修改数据:
- **插入新的部门元组**:
```sql
INSERT INTO DEPT:
< 'D36' 'ECONOMICS' 400>;
```
- **删除部门元组**:
```sql
DELETE DEPT
WHERE DNO = 'D15';
```
- **增加部门预算**:
```sql
UPDATE DEPT
SET BUDGET = BUDGET + 20
WHERE DNO = 'D15';
```
- **给部门D7的导师加薪10%**:
```sql
UPDATE TUTOR
SET SAL = SAL * 1.1
WHERE TDN = 'D7';
```
##### 1.3 SQL函数
SQL支持多种统计函数,如COUNT、SUM、AVG、MAX和MIN:
- **统计TUTOR关系中不同部门的总数**:
```sql
SELECT COUNT (UNIQUE TDN)
FROM TUTOR;
```
- **统计DEPT表中的元组数量**:
```sql
SELECT COUNT (*)
FROM DEPT;
```
- **按部门计算平均薪资并按薪资值排序**:
```sql
SELECT AVG (SAL)
FROM TUTOR
GROUP BY TDN
ORDER BY AVG (SAL);
```
- **计算部门的平均周预算**:
```sql
SELECT AVG (SAL)/52
FROM DEPT;
```
- **查询除D15外各部门的编号和平均薪资**:
```sql
SELECT TDN, AVG (SAL)
FROM TUTOR
WHERE TDN != 'D15'
GROUP BY TDN;
```
- **查询除D15外有超过两名导师的部门编号**:
```sql
SELECT TDN
FROM TUTOR
WHERE TDN != 'D15'
GROUP BY TDN
HAVING COUNT (*) > 2;
```
##### 1.4 SQL数据定义
SQL不仅可以进行数据操作,还可以进行数据定义,如定义视图、授权和设置完整性约束:
- **定义视图V30**:
```sql
DEFINE VIEW V30 AS
SELECT TNO, SAL
FROM TUTOR
WHERE TDN NOT IN (D20, D32);
```
- **授权**:
```sql
GRANT READ, INSERT, UPDATE ON TUTOR TO BILBO, FRODO
WITH GRANT OPTION;
```
- **完整性约束**:
- **断言导师薪资不超过30K**:
```sql
ASSERT A1 ON TUTOR: SAL <= 30;
```
- **断言TUTOR表中的TNO值必须存在于DEPT表的DNO中**:
```sql
ASSERT A2
(SELECT TNO FROM TUTOR
IS IN
SELECT DNO FROM DEPT);
```
- **断言导师的新薪资不能低于旧薪资**:
```sql
ASSERT A3 ON UPDATE OF TUTOR (SAL) NEW SAL >= OLD SAL;
```
#### 2. QBE语言
0
0
复制全文
相关推荐









