oracle -连接查询

1.内连接

  内连接通常称为连接,内连接发生在从两个表中选取记录且第一个表中某一列的值能在第二个表的相同列中找到 ,实际中,两个或者多个表连接是基于共同的字段。 一般这些共同字段都是主键

  示例:select prod_id ,quantity_sold,cust_city,cust_state_province

         from sales ,customers

         where  sales.cust_id =  custmoers.cust_id

         and prod_id = 117;

 如果连接的表比较多,就很有可能混乱,所以有必要为你表的指定别名 来实现内联的查询

  示例: select  s.cust_id ,s.prod_id ,s.quantity_sold,c.cust_city,c.cust_state_province

         from sales s  ,customers c

         where  s.cust_id =  c.cust_id

         and s.prod_id = 117;

2ANSI 内连接

  ANSI on /using  可以使用on 或者using 语句来指定一个简单连接,被连接的列在 on/using 字句中列出,而where 字句中可以列出附加的选择标准

  示例:select  s.cust_id ,s.prod_id ,s.quantity_sold,c.cust_city,c.cust_state_province

         from sales s   join customers c

         using (cust_id )

         and s.prod_id = 117;

 ANSI 语法也允许两个或者多个表的连接,可以在sql 语句的from 部分使用多重join on 或者 join using 来完成

 示例: select  c.cust_id ,c.cust_state_province, s.quantity_sold, p.prod_name

         from sales s

         join  customers c   on  s.cust_id = c.cust_id

         join products   p  on p.prod_id = s.prod_id

         where p.prod_id  =117 and c.country_id= 5267;

  或者:

       select  cust_id ,c.cust_state_province, s.quantity_sold, p.prod_name

         from sales s

         join  customers c  using(cust_id)

         join products   p   uisng (prod_id)

         where p.prod_id  =117 and c.country_id= 5267;

  备注:on 连接语法告诉oracle 在表中连接要使用那些列,与oracle 的内连接类似,在select 中列都需要添加前缀来区别。

          using 语法只声明列名,并且允许oracle 对连接进行解析。cust_id 列的限定词不能出现在select 中和连接部分。

2.外连接

   从一个表中找出另一个表中没有的任何匹配的行,也就是所谓 的外连接。oracle 用符号“(+)” 。“(+)” 可以出现在where 字句中任一个表后。要求查询返回另一个表中无匹配的记录行

  示例: select  c.cust_id ,c.cust_last_name ,s.prod_id , s.quantity_sold

           from  customers c , sales s

           where  c.cust_id  = s.cust_id (+)

           and  c.cust_id in (1,80);

  备注:sales 的左外连接

  或者:左链接

  示例: select a. id,desc1,desc2

          from  temp2 b left join temp1 a

          on b.id =a.id;

          右连接:

  示例:select a.id  ,desc1,desc2

          from  temp1 a right join temp2 b

         on a .id  =b. id ;

         完全外连接

  示例: select a.id ,desc1,desc2

        from tmep1 a full join temp2 b

        on a.id =b.id ;

3.自连接

   自连接用于建立单个表内 关联,返回的行于同一个表进行连接,而不是与第二个相关表进行连接。

   create table family

   (

    name  char(10),

    birth_year number(4),

    Father  char(10)

    )

 示例: select  a.name ,a.birth_year ,a .father,b.brith_year

         from family a ,family b  , family c

         where  a.father  = b .name ;

 

          

原文地址:https://www.cnblogs.com/linsu/p/3315888.html