站长资讯网
最全最丰富的资讯网站

Oracle学习之using关键字(实例详解)

本篇文章给大家带来了关于Oracle的相关知识,其中主要介绍了关于using关键字的相关知识,可以使用using关键字来简化连接查询,希望对大家有帮助。

Oracle学习之using关键字(实例详解)

推荐教程:《Oracle教程》

在工作中,查看到类似于如下的SQL语句:

select      tb.usrnm,      tb.typ,      tb.oprorder      from tb     inner join rb1     using (stfaprid)      where tb1.jugsumid = #jugsumid#      and tb1.blnorg = #blnorg#      and isvld = '1'      order by tb.typ asc, tb.oprorder asc

sql/92标准可以使用using关键字来简化连接查询,但是只是在查询满足下面两个条件时,才能使用using关键字进行简化。

  • 1.查询必须是等值连接。
  • 2.等值连接中的列必须具有相同的名称和数据类型。

例如:使用using关键字,如下:

select emptno,ename,sal,deptno,dname from emp e inner join dept d using(deptno);

如上述语句执行的结果与自然连接的结果相同。
使用using关键字简化连接时,需要注意以下几点:

  • 1.使用emp表和dept表中的deptno列进行连接时,在using子句和select子句中,都不能为deptno列指定表名或表别名。
  • 2.如果在连接查询时使用了两个表中相同的多个列,那么就可以在using子句中指定多个列名

形式如下:

select... from table1 inner join table2 using(column1,column2)

上述的语句相当于下面的语句:

select... from table1 inner join table2 on table1.column1=table2.column2 and table1.column2=table2.column2;

如果对多个表进行检索,就必须多次使用using关键字进行指定,形式如下:

select... from table1 inner join table2 using(column1) inner join table3 using(column2);

上述的语句相当于下面的语句:

select... from table1,table2,table3 where table1.column1=table2.column1 and table2.column2=table3.column2;

再议using

在Oracle中的join连接中使用using关键字,是相对于natural join的。
我们在前面提到,如果是使用natraul join,并且两张表中如果有多个字段是具有相同的名称和数据类型的,那么这些字段都将被oracle自作主张的将他们连接起来。
但实际上我们有时候是不需要这样来连接的。我们只需要将他们的多个具有相同的名称和数据类型的字段中挑选一两个。这时候我们就需要用到using 关键字了。下面是一个例子。
有一个表是sales,还有一个表是costs,这两个表中都有两个字段分别是pro_id和time_id。我们暂且不去考虑下面连接的实际意义,仅作语法上的研究。
如果使用natural连接,默认情况下,两个字段将会被自然地连接在一起。

Select * from Sales natural join costs;

Select * from Sales join costs on Sales.prod_id = costs.prod_id and sales.time_id = costs.time_id

Select * from Sales ,costs Where Sales.pro_id = cost.prod_id and sales.time_id = costs.time_id

得到的结果应该是一样的。
如果我们使用自然连接,就没有机会控制连接条件,oracle自作主张的将两个相同数据类型和名称的字段自然地连接在一起了。
下面我们使用using关键字。

Select * from Sales join costs using(prod_id)

这样就迫使oracle使用using指出的字段来做连接,而不是natural join连接中默认的两个。
请注意,这里的SQL语句没有任何意义,只是为了说明using的用法举了一个牵强的例子而已。
这里还需要说明的是:
如果在使用using关键字时,而且select的结果列表项中包含了using关键字所指明的那个关键字,那么请不要在select的结果列表项中对该关键字指明它属于哪个表,例如如果使用using(prod_id),而在结果列表中要包含prod_id字段的话,请不要写成sales.prod_id或者costs.prod_id而应该写成prod_id,而且也不要使用别名,就是使用例如prod_id as “产品编号”的形式。

  • using中仅能使用一个列名。
  • natural join关键字和using关键字是互斥的,也就是说不能同时出现。

推荐教程:《Oracle视频教程》

赞(0)
分享到: 更多 (0)