码迷,mamicode.com
首页 > 数据库 > 详细

Oracle数据库(三)表操作,连接查询,分页

时间:2017-08-14 16:39:24      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:cache   new   join   eve   let   连接   解决   acl   生成   

复制表

--复制表
create table new_table as select * from Product
--复制表结构不要数据
create table new_table as select * from Product where 1=2

在where后面跟一个不成立的条件,就会仅复制表的结构而不复制表的内容。

删除表

--删除表
delete table new_table
--删除表,无法找回
truncate table new_table

序列

序列(SEQUENCE)其实是序列号生成器,可以为表中的行自动生成序列号,产生一组等间隔的数值(类型为数字)。其主要的用途是生成表的主键值,可以在插入语句中引用,也可以

通过查询检查当前值,或使序列增至下一个值。

 使用语句创建序列

----创建序列
create sequence user_seq
increment by 1 
start with 1
nomaxvalue
nominvalue
nocache

多表查询

select * from p_emp e ,p_dept d where e.deptno=d.deptno

 

笛卡尔积

 笛卡尔积在sql中实现的方式是交叉连接,所有连接方式都会先生成临时笛卡尔积表,笛卡尔积是关系代数的一个概念,表示两个表中每一行数据任意组合。

简单来说,就是两个表不加条件限制的进行连接,出现的数据行数是两个表数据行数的乘积。

内连接

select * from p_emp e ,p_dept d where e.deptno=d.deptno

内连接的局限性:如果有空值,查询结果可能会有缺失。

解决办法:

以一个表为基准进行外链接:

--左外链接
select * from p_emp e left join p_dept d on e.deptno=d.deptno

或者使用 +  符号

select * from p_emp e, p_dept d where e.deptno=d.deptno(+)

 查询用户的表

--查询所有表
select * from user_tables

自连接

有些情况可能会遇到,将一个表的相同或者不同列的数据进行比较,需要将一个表来进行当做两个表进行自连接,进而比较其中的数据再进行查询

--自连接
select e1.ename,e2.ename from p_emp e1,p_emp e2 where e1.empno=e2.mgr

层次查询

oracle中的select语句可以用START WITH...CONNECT BY PRIOR子句实现递归查询,connect by 是结构化查询中用到的,其基本语法是:

select ... from <TableName>

where <Conditional-1>

start with <Conditional-2>

connect by <Conditional-3>

;

<Conditional-1>:过滤条件,用于对返回的所有记录进行过滤。

<Conditional-2>:查询结果重起始根结点的限定条件。

<Conditional-3>:连接条件

--层次查询
select e.*,level from p_emp e connect by prior e.empno=e.mgr start with e.ename=KING order by level

伪列:
level
rownum

rownum是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,依此类推,这个伪字段可以用于限制查询返回的总行数,

而且rownum不能以任何表的名称作为前缀。

需要注意的是:如果按照主键排序,rownum的顺序会跟着变化,如果不是按照主键排序,rownum不会变。

--查询前十列数据
select e.*,rownum from p_emp e where rownum <=10
--6-10列数据,嵌套查询
select * from (select e.*,rownum rownu from p_emp e where rownum <=10) r where r.rownu >5 

Oracle数据库(三)表操作,连接查询,分页

标签:cache   new   join   eve   let   连接   解决   acl   生成   

原文地址:http://www.cnblogs.com/jiangwz/p/7345342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!