Oracle
关于oracle数据库的一些基本使用笔记”
表结构操作
创建表
create table tableName (id varchar2(36) primary key, name varchar2(36), age number(12,2), createDate date, modifyDate date);
-- 创建一张表,表名:tableName,-- 字段 id 字符串类型 主键,name 字符串类型普通字段,age 数字类型,createDate 创建日期,modifyDate 修改日期
添加表字段
alter table tableName add (address varchar2(32) default '无',country varchar2(32) default '');--给表添加 address 和 country字段 都是32位长度的字符串类型
添加字段描述
COMMENT ON COLUMN tableName.address IS '地址';
删除表字段
alter table tableName drop column country; --删除表的country字段
表数据操作
sql表的设计是很重要的,涉及业务与拓展及后期维护,但是核心应该是:简单
查询表内容
select * from tableName; --查询表所有内容select name,age from tableName; --查询表name字段和age字段
子查询
select a.name, a.age , (select b.hobby from kid b where b.name = a.name and rownum = 1) hobbyfrom student a where a.id = 'id'
查询总数
select count(1) from tableName; -- 不统计 nullselect count(*) from tableName; -- 统计 null
按条件查询 where
select * from tableName where age >= 18; --查询表中age大于18的所有数据
插入数据
insert into tableName(field1,field2) values('value1','value2');
提交
commit
撤回
rollback
综合查询
并行查询
多表查询并集
select T1.id,T1.name,T1.age from table1 T1 where T2.age < 16unionselect T2.id,T2.name,T2.age from table2 T2 where T2.age <16unionselect T3.id,T3.name,T3.age from table3 T3 where T3.age < 16-- 这里 三张不同的表,只需要三张表都有 id,name,age 字段(字符集也要相同,查询结果需要统一类型),就可以查三张表的并集
union all 与 union 区别
两个都是查询多表的并集 ,union all 会出现重复数据(所有字段值相等的), 但是 union 不会出现重复数据(所有字段值相等的)。
to_char to_nchar
字符集不匹配时可用解决方案
使用trim函数去除字符串的空格’ ’
select trim(' ss') from dual;
查询结果为’ss’ 而不是’ ss’
表连接查询
inner join 与 left join 的区别
inner join 没有主表与副表之分,left join 有主表副表之分 假如,A表有三条数据,B表有2条数据 他们是关联对应的,那么 inner join 能查出两条,left join 能查出三条 select * from A inner join B on (查询条件) => 得到两条数据
select * from A left join B on (查询条件) => 得到三条数据(主表A有三条)
case 用法
有两种用法
比较值
select T.name, T.area, case T.age when '18' then '刚成年' when '20' then '刚20' else T.age end as age, from student T
作为搜索条件
select T.name, T.area, case when T.age ='18' then '刚成年' else T.age end as age, from student T