二、SQL数据库的查询和操作

二、SQL数据库的查询和操作

一、常用的类型

 1char(10):当数据小于10个字节时自动添加空格补齐

 2varchar2(10):数据小于10个字节时oralce自动判断识别数据的字节大小

 3number(4,2) :数据必须总长度是4位,小数点后没有也要占2位的数字(不包括小数点)

 注意:小数点强制先占两位,再看整数位,小数点后超出范围四舍五入,整数不可以

 4date:储存日期和时间 如果添加日期没有时间自动补齐12:00:00

 5Timestamp:比date多了一个时区

 

二、创建表和约束

1、create table student

(

 infos varchar2(7)not null,  --学号

 stuname varchar2(10)not null, --姓名

 gender varchar2(2) not null, -- 性别

 age number(2) not null, --年龄 number为整数不能有小数点

 seat number(2) not null, --座号

 enrolldate date, --入学时间

 stuaddeess varchar2(50) default'地址不详', --住址

 classno varchar2(4) not null --班号   =学期序号+班级序号

);

2、约束就是规定一个数据的值范围和值规则

3、添加约束:alter table 表名 add constraint 约束名 约束内容

-- 添加主键约束

alter table infos add constraint pk_infos primary key(stuid);

-- 添加列约束性别约束为男女

alter table infos add constraint ck_infos_gender check(gender in('',''));

-- 约束座号为050

alter table infos add constraint ck_infos_seat check(seat>=0 and seat<=50);

-- 约束年龄0100

alter table infos add constraint ck_infos_age check(age between 0 and 100 );

-- 约束 班号

alter table infos add constraint ck_infodfss_classno check((classno between 1 and 1999) or (classno between 2000 and 2999));

--注意:如果数据中有数据 check时要注意取包括数据在内范围值

 

定义外键:alter table 表名 add constraints fk_emp_dept foreign key(列名) references 引用表名(列名); 

注意:使用外键时,引用表数据必须包括添加外键的表数据

 缓存区就是储存在内存条里还未写入数据库或者说硬盘的数据 commit;结尾可以将他写入进去

 

三、数据库操作语言 

 1、结果集做数据源:create table 表名 as select语句

 2to_date(‘字符串’,’格式’)将字符串转换日期格式:to_date(‘2009/8-9 6:7:8’;’yyyy/mm/dd hh24:mm:ss’);

 3truncatedelete类似 只是删除数据后无法通过日志恢复

 4select distinct 列名或者* from 表名;

 5、判断是否为nul不能用 必须用is或者not,例如:select * from emp where ename is null;

 6in操作: where sal in(‘1000’,’2000’,’3000’);当等salin中值时就输出

 7between and 返回两个值之间范围包括两值:select *from emp where sal between 1000 and 2000;输出工资10002000的记录

 8、通配符 s%:以S开头的字符串,_s%:第二个字符是S的字符串

 9、当要查询中出现带有%的数据时,使用通配符时就需要用到转义字符否则%当通配符读取: select * from studenta where name like '%30\%%'escape'\'查询name=30%的数据

 

四、集合运算

-- intersect交集(返回两个集合之间所有不相同的数据)

-- union all 并集 (返回查询的所有记录 包括重复)

-- union 并集 不包括重复值

-- minus 补集(返回两个集合不相同的值)

使用方法:求补运算

select deptno from dept

minus

select deptno from emp;

 

五、Union(并集插入多条数据

Insert into dept

Select语句

Union

Select语句

 

六、联接查询

1、内联接

 Select e.列名,d.列名 from emp e,dept d where e.deptno=d.deptno; 

 Select e.列名,d.列名 from emp e inner join dept d on e.deptno=d.deptno; 

 

2、外连接(通常联接没有外键的表)

 Select e.列名,d.表名 from emp e left join dept d on e.deptno=d.deptno where sal=1000; 

注意:外连接中有leftright left是以join左边的表做为主表联接 on联接条件 on联接完后会把主表中没有参加过联接的记录也显示出来

然后就where挑选数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值