Oracle - 多表查询

来源:互联网 发布:wp软件下载 编辑:程序博客网 时间:2024/05/24 05:04
Oracle - 多表查询

一、笛卡尔集
    > 笛卡尔集是集合的一种,假设A和B都是集合,A和B的笛卡尔积用A X B来表示,是所有有序偶(a,b)
       的集合,其中a属于A,b属于B。
1、笛卡尔集的产生条件:
    > 省略连接条件
    > 连接条件无效
    > 所有表中的所以行互相连接

2、避免笛卡尔集的方法:在 where 中加入有效的连接条件

二、内连接和外连接
    > 内连接:合并具有同一列的两个以上的表的行,结果集中不包含一个表与另一个表不匹配的行
    > 外连接:两个表在连接过程中除了返回满足连接条件的行以外还返回左(或右)表中不满足条件的行,
                     这种连接称为左(或右)外连接。没有匹配的行时,结果表中相应的列为null,外连接的where
                     子句条件类似于内部连接,但连接条件中没有匹配行的表的列后面要加外连接运算符,即
                     用圆括号括起来的加号(+)

1、外连接语法:使用外连接可以查询不满足连接条件的数据,外连接的符号是:加号(+)
select table1.name, table2.name
from table1, table2
where table1.id(+) = table2.id;                 // 右外连接

select table1.name, table2.name
from table1, table2
where table1.id = table2.id(+);                 // 左外连接

2、自连接:
select a.name, b.name
from table a, table b
where a.id = b.id;                 // 右外连接

3、等值连接:使用连接在多个表中查询数据
select table1.name, table2.name
from table1, table2
where table1.id = table2.id;

4、叉集:使用 cross join 子句使连接的表产生叉集
select id,name
from tablename
cross join tablename2;

5、表的别名:使用别名可以在多表查询时,简化书写
select a.name, b.name
from table1 a, table2 b
where a.id = b.id;
0 0