令人惊讶的是,“关系”数据库中的“关系”does not指一个表与另一个表的外键关系。根据维基百科的说法,“关系是一种数据结构,由标题和一组无序的共享相同类型的元组组成”'关系(数据库)' http://en.wikipedia.org/wiki/Relation_(database).
在 SQL RDBMS(例如 MS SQL Server 和 Oracle)中,表是永久存储的关系,其中数据字典中定义的列名形成“标题”,行是关系的“元组”。
然后,查询可以从表中返回不同的关系:
create table t (x number primary key, y number not null);
Table created.
SQL> insert into t values (1, 10);
1 row created.
SQL> insert into t values (2, 20);
1 row created.
SQL> select x from t;
X
----------
1
2
select x from t
返回的关系比基表具有更少的列、更少元素的元组。和select x, y from t where x = 1
将返回元组数少于基表的关系:
SQL> select x, y from t where x = 1;
X Y
---------- ----------
1 10
使用内连接的示例:
SQL> create table s (x number primary key, words varchar2(100) not null);
Table created.
SQL> insert into s values (1, 'Hello World!');
1 row created.
SQL> insert into s values (3, 'Will not show');
1 row created.
SQL> select t.x, t.y, s.words
2 from t
3 inner join s
4 on t.x = s.x;
X Y WORDS
---------- ---------- ---------------
1 10 Hello World!
从概念上讲,t inner join s on t.x = s.x
经过以下步骤:
-
取笛卡尔积s
and t
,即取每一行s
并将其与每一行组合t
得到一个元组s 的大小 * t 的大小元组或行,每个元组或行都包含来自元组或行的所有列s
and t
很像以下的结果:
SQL> 从 s, t 选择 *;
X WORDS X Y
3 Will not show 1 10
3 Will not show 2 20
1 Hello World! 1 10
1 Hello World! 2 20
(Or select * from s cross join t
在 SQL-92 语法中)来自包含四个元组/行和四列的笛卡尔积on s.x = t.x
将元组修剪为一个,但仍然有四列:
SQL> select *
2 from t
3 inner join s
4 on t.x = s.x;
X Y X WORDS
---------- ---------- ---------- ---------------
1 10 1 Hello World!
And select t.x, t.y, s.words
从关系中删除一列。
Note上面描述了正在发生的事情的概念或逻辑模型。数据库带有查询优化器,旨在提供结果,就好像所有逻辑步骤都已遵循一样,但在工作的物理实现中设法跳过步骤,并使用不属于其一部分的支持物理结构,例如索引的关系模型。
视图是关系定义,它不存储关系,而是基于其他关系定义关系,最终在底部定义表。 (物化视图除外,它们根据其他关系预先计算并存储关系。)