0%

3.4.5 where子句谓词

3.4.5 where子句谓词

between and

为了简化where子句,SQL提供between比较运算符来说明一个值是小于或等于某个值,同时大于或等于另一个值的

如果我们想找出工资在90000美元和100000美元之间的教师的姓名,我们可以使用between比较运算符,如下所示:

1
2
3
select name
from instructor
where salary between 90000 and 100000;
1
2
3
4
5
6
7
8
9
10
11
mysql> select name
from instructor
where salary between 90000 and 100000;
+----------+
| name |
+----------+
| Wu |
| Einstein |
| Brandt |
+----------+
3 rows in set

它可以取代:

1
2
3
select name
from instructor
where salary <=100000 and salary >=90000;
1
2
3
4
5
6
7
8
9
10
11
mysql> select name
from instructor
where salary <=100000 and salary >=90000;
+----------+
| name |
+----------+
| Wu |
| Einstein |
| Brandt |
+----------+
3 rows in set

not between and

类似地,我们还可以使用not between比较运算符。

1
2
3
select name
from instructor
where salary not between 90000 and 100000;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mysql> select name
from instructor
where salary not between 90000 and 100000;
+------------+
| name |
+------------+
| Srinivasan |
| Mozart |
| El Said |
| Gold |
| Katz |
| Califieri |
| Singh |
| Crick |
| Kim |
+------------+
9 rows in set

类似地,我们还可以使用not between比较运算符。

(n元组) 比较运算符 (n元组)

SQL允许我们用记号(V1,V2,…,Vn)来表示一个分量值分别为V1,V2,...,Vn的n维元组。

n元组将按字典顺序比较

在元组上可以运用比较运算符时将按字典顺序进行比较运算
例如,(a1,a2)<=(b1,b2)a1<=b1a2<=b2时为真。

所有属性相等n元组相等

类似地,当两个元组在所有属性上相等时,它们是相等的。

SQL查询 査找Biology系讲授了课程的所有教师的姓名和他们所讲授的课程的课程号

一般形式

为了写出这样的查询,我们可以在前面看到过的两个SQL查询的任意一个的基础上进行修改,在where子句中增加一个额外的条件。我们下面给出修改后的不使用自然连接的SQL查询形式:

1
2
3
select name,course_id
from instructor,teaches
where instructor.ID= teaches.ID and dept_name = 'Biology';
1
2
3
4
5
6
7
8
9
10
mysql> select name,course_id
from instructor,teaches
where instructor.ID= teaches.ID and dept_name = 'Biology';
+-------+-----------+
| name | course_id |
+-------+-----------+
| Crick | BIO-101 |
| Crick | BIO-301 |
+-------+-----------+
2 rows in set

n元组比较形式

使用n元组比较可以将上面的一般形式重写为如下形式:

1
2
3
select name, course_id
from instructor,teaches
where (instructor.ID, dept_name ) = (teaches.ID, 'Biology');
1
2
3
4
5
6
7
8
9
10
mysql> select name, course_id
from instructor,teaches
where (instructor.ID, dept_name ) = (teaches.ID, 'Biology');
+-------+-----------+
| name | course_id |
+-------+-----------+
| Crick | BIO-101 |
| Crick | BIO-301 |
+-------+-----------+
2 rows in set

大学数据库模式

教室:classroom(building,room_number,capacity)
系:department(dept_name,building,budget)
课程:course(course_id,title,dept_name,credits)
授课:teaches(ID,course_id,sec_id,semester,year)
讲师:instructor(ID,name,dept_name,salary)
section(course_id,sec_id,semester,year,building,room_number,time_slot_id)
学生:student(ID,name,dept_name,tot_cred)
takes(ID,course_id,sec_id,semester,year,grade)
advisor(s_ID,i_ID)
time_slot(time_slot_id,day,start_time,end_time)
prereq(course_id,prereq_id)

原文链接: 3.4.5 where子句谓词