数据库
表与表 的设计
主外键的约束关系
- 从表中的外键字段的值参考了主表中的外键字段的值
- 主表:被引用的
- 从表:定义了外键字段存在的表
三范式
- 列不可再分,字段的原子性
- 定义主键区分唯一 (非主键字段必须都依赖于主键字段)
- 通过主外键关联关系确定,避免数据的重复冗余
select
去重
distinct:对结果集中完全相等的两条数据只显示一条
select distinct deptno from emp;
伪列
select distinct 123 from emp
字符串的拼接||
select ‘hdih’||ename from emp
别名
表的别名不用as,字段的别名as可有可无
虚表
select 123*475 from,sysdate from dual
null值
- null值与数字运算,结果是null:select comm+100 from emo
- null值与字符串运算,结果是原串
- nvl(值一,值2):当值不为null时,函数的最终结果是值二
条件查询
集合函数
- union并集
- union并集(去重)
- insersect交集
- minus差集
模糊查询
- %:任意个字符
- _:一个任意字符
- eacape()里面的是转义符
select * from emp where ename like ‘%%%’ eacape(’’)
exists
存在即保留
select * from emp where exists(select deptno from dept where dname in (‘SALES’,‘ACCOUNTING’) and dept.deptno =emp.deptno );
函数
单行函数
- 当前时间:sysdate ,current_date
- add_months(日期对象,月份数):
- trunc()对()中的数据取整
- round(数据,几位小数)
- last_day():查询当前月的最后一天
- next_day(日期对象,星期几):下一个星期几是几号
- 日期对象转日期字符串:to_char(日期对象,‘模板’)
- 日期字符串转日期对象:to_date(日期字符串,‘模板’)
多行函数
1.多行函数即组函数即聚合函数
2.一旦在select后面使用了组函数,只能和其它组函数和分组字段一起使用,null不参与组函数计算
3.分组:
- group by 分组字段
- 执行流程:from -->where–>group by–>select–>order by
4.多行函数有:max() min() count() sum() avg()等
5.原因:因为一旦分组,无法知道每组有多少条数据,每个字段是什么值也不能确定,where不能使用组函数
6.例子:select dname from dept where deptno in (select deptno
from emp
group by deptno
having avg(sal) = (select min(avg(sal)) from emp group by deptno));
判定函数
语法:decode(condition,case1,express1,case2,express2…,默认值)
解释:如果条件condition和case1相等,结果就为express1,如果case2,结果就为express2,以此类推,否则为默认值
例子:查询部门信息,为部门添加一列中文名称,10->十 20->二十…
select deptno,dname,loc,decode(deptno,10,‘十’,20,‘二十’,30,‘三十’,40,‘四十’,‘未定义’) 中文名称 from dept;
语法:case when then else end
例子:查询员工信息计算员工涨薪后的薪水,30部门的员工薪资上调10%
select empno,ename,sal,deptno,decode(deptno,30,sal*1.1,sal) 涨薪后薪水 from emp;
–case when then else end
select ename,
sal,
deptno,
(case deptno
when 10 then
sal * 1.1
when 20 then
sal * 1.08
when 30 then
sal * 1.15
else
sal * 1.2
end) raisesal
from emp;
行转列
表连接
92语法表连接
内连接:满足连接条件显示,不满足不显示
外连接:不满足条件也可以显示,主表的对面添加+
- 左外连接:主表在左边,
- 右外连接:主表在右边
99语法表连接
内连接:满足连接条件显示,不满足不显示
- 笛卡尔积:cross join
- 自然连接:natural join,只能做等值连接
- join using :只能做等值连接
- join on:等值和非等值连接都可以
外连接:不满足条件也可以显示
- 左外连接:left join主表在左边
- 右外连接:right join主表在右边
- 全连接:full join 两张表都是主表