unique
unique结果为真的情况
unique结果为假的情况
注意空值
`SQL`查询 找出所有在2009年最多开设一次的课程
`MySQL`好像不支持`unique`结构
not unique
`MySQL`也不支持`not unique`
3.8.4 重复元组存在性测试
unique
SQL
提供一个unique
结构用于测试在一个子查询的结果中是否存在重复元组。
unique结果为真的情况
如果作为参数的子查询结果中没有重复的元组, unique
结构将返回true
值。
unique结果为假的情况
当且仅当在关系中存在着两个元组t1和t2,且t1=t2时unique
测试结果为假
注意空值
由于在t1或t2的某个域为空时,判断t1=t2为假,所以尽管一个元组有多个副本,只要该元组有一个属性为空, unique
测试就有可能为真。
SQL
查询 找出所有在2009年最多开设一次的课程
我们可以用unique
结构书写查询”找出所有在2009年最多开设一次的课程”,如下所示:1
2
3
4
5
6
7select T.course_id
from course as T
where unique(
select R.course_id
from section as R
where T.course_id=R.course_id and R.year=2009
);
注意如果某门课程不在2009年开设,那么子查询会返回一个空的结果, unique
谓词在空集上计算出真值。
MySQL
好像不支持unique
结构
在不使用unique
结构的情况下,上述查询的一种等价表达方式是1
2
3
4
5
6
7select T.course_id
from course as T
where 1 >=(
select count(R.course_id)
from section as R
where T.course_id =R.course_id and R.year=2009
);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24mysql> select T.course_id
from course as T
where 1 >=(
select count(R.course_id)
from section as R
where T.course_id =R.course_id and R.year=2009
);
+-----------+
| course_id |
+-----------+
| BIO-101 |
| BIO-301 |
| BIO-399 |
| CS-101 |
| CS-315 |
| CS-319 |
| CS-347 |
| EE-181 |
| FIN-201 |
| HIS-351 |
| MU-199 |
| PHY-101 |
+-----------+
12 rows in set
not unique
我们可以用not unique
结构测试在一个子查询结果中是否存在重复元组。为了说明这一结构,考虑查询”找出所有在2009年最少开设两次的课程”,如下所示:1
2
3
4
5
6
7select T.course_id
from course as T
where not unique(
select R>course_id
from section as R
where T.course_id= R.course_id and R.year=2009
);