Oracle数据库学习(二)

2.用SQL进行多表查询

  1)无条件多表查询

       笛卡尔集:总记录数=table1记录数×table2记录数

       select * from table1, table2

  2)等值连接

       内连接:select tab1.f_z, tab2.* from table1 tab1, table2 tab2 where tab1.f_z = tab2.f_c。

       左外连接(包括没有单位的机型):select tab1.f_z, tab2.* from table1 tab1, table2 tab2 where tab1.f_z = tab2.f_c(+)。

       右外连接(包括没有机型的单位):select tab1.f_z, tab2.* from table1 tab1, table2 tab2 where tab1.f_z(+) = tab2.f_c。

       实际使用中,建议外连接统一使用左外连接;查询字段和连接条件中,若两表都有相同的字段名,必须指定字段对应的表名。

3.用SQL进行嵌套查询

也叫子查询,子查询形成的结果又成为父查询的条件。

in、exists:如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in;反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists。

not in、not exists:不推荐not in,会导致两个表的全表扫描,尽量转换为minus重写;not exists效率一般比较高;根据实际执行计划调试。

union(并集):select 1 as f_id, ‘是’ as f_m from tab union select 0 as f_id, ‘否’ as f_m from tab

intersect(交集)、minus(差集)

并、交和差操作的嵌套查询要求属性具有相同的定义,包括类型和取值范围。

 

4.用SQL进行函数查询

 

  1)函数:

Round、Count、Sum、Avg、Min、Max

 

  2)条件表达式:nvl、decode、case when

 

       select nvl(f_z, 0) from table;如果f_z为空,返回0;否则为f_z。

 

       select decode(f_z, 1 , '客机', '货机') from table

 

       select case when f_z = 1 then '客机' else '货机' end from table

 

case语句在处理相似问题就显得比较简捷灵活。另外,当需要匹配少量数值时,选用decode会更加方便一些。

5.Dual的使用

Dual是Oracle中实际存在的一种表,任何用户都可以使用,常用在没有目标表的select语句中。可用于查看时间、用户、计算等;select user from dualselect sysdate from dual

 

posted @ 2018-03-26 13:47  lvanka  阅读(209)  评论(0编辑  收藏  举报