Mastering Oracle SQL学习笔记(join句法专题第二部份)

3 Natrue Join 从句
      两个表之间的关联,是基于它们的关联列。如果这两个表中的关联列名字相通,那么我可以不必指定它们的连接条件。下面是一个描述 Natrue 关联的例子:
 
SELECT department.name, location.regional_group
 
FROM department NATURAL JOIN location;
 
      如果你要在 SELECT 列表中中选出两个表公共的列,则不能在此列名前加表名或表别名,如( department. location_id ),看下面的举例:
 
SELECT department.location_id, department.name, location.regional_group
 
FROM department NATURAL JOIN location;
 
SELECT department.location_id, department.name, location.regional_group
 
       *
 
ERROR at line 1:
 
ORA-25155: column used in NATURAL join cannot have qualifier
 
很显然报错了,那我们应该写成什么样呢:
 
SELECT location_id, department.name, location.regional_group
 
FROM department NATURAL JOIN location;
      不明确的 Natrue Join 条件将会得到我们不想得到的结果:用下面举像说明 :
 
DESC supplier (supplier 表的表定义 )
 
 Name                                      Null?    Type
 
 ----------------------------------------- -------- --------------
 
 SUPPLIER_ID                               NOT NULL NUMBER(5)
 
 NAME                                      NOT NULL VARCHAR2(30)
 
 
 
DESC part (part 表的表定义 )
 
 Name                                      Null?    Type
 
 ----------------------------------------- -------- --------------
 
 PART_NBR                                  NOT NULL VARCHAR2(20)
 
 NAME                                      NOT NULL VARCHAR2(30)
 
 SUPPLIER_ID                               NOT NULL NUMBER(5)
 
 STATUS                                    NOT NULL VARCHAR2(20)
 
 INVENTORY_QTY                                      NUMBER(6)
 
 UNIT_COST                                          NUMBER(8,2)
 
 RESUPPLY_DATE                                      DATE
 
在下面的 Join 查询语句 , 得出下面的结果:
 
SELECT supplier.supplier_id, part.part_nbr
 
FROM supplier JOIN part
 
ON supplier.supplier_id = part.supplier_id;
 
 
 
SUPPLIER_ID PART_NBR
 
----------- -----------
 
          1 AI5-4557
 
          2 TZ50828
 
          3 EI-T5-001
 
我们将上面的语句改成 Natrue Join 语句,看看结果:
 
SELECT supplier_id, part.part_nbr
 
FROM supplier NATURAL JOIN part;
 
 
 
no rows selected
 
没有输入,怎么回事?其原因就在于在 supplier 表和 part 表中有两个同名的列( supplier_id name ),此时 Natrue Join 它就不知道是关联哪个列,于是索性两个一起关联,用常规的 Join 语句表示就是:
 
SELECT supplier.supplier_id, part.part_nbr
 
FROM supplier JOIN part
 
ON supplier.supplier_id = part.supplier_id
 
AND supplier.name = part.name;
 
明白了吧!我们可以用 using 从句得到我们想要的结果:
 
SELECT supplier_id, part.part_nbr
 
FROM supplier JOIN part
 
USING (supplier_id, name);
 

你可能感兴趣的:(oracle,数据库,职场,休闲)