天天看点

#yyds干货盘点#常见SQL面试题

SQL基础知识整理

select 查询结果,如: [学号,平均成绩:组函数avg(成绩)]

from 从哪张表中查找数据,如:[涉及到成绩:成绩表score]

where 查询条件,如:[b.课程号='0003' and b.成绩>80]

group by 分组,如:[每个学生的平均:按学号分组](oracle,SQL server中出现在select 子句后的非分组函数,必须出现在group by子句后出现),MySQL中可以不用

having 对分组结果指定条件,如:[大于60分]

order by 对查询结果排序,如:[增序: 成绩  ASC / 降序: 成绩 DESC];

limit 使用limt子句返回topN(对应这个问题返回的成绩前两名),如:[ limit  2 ==>从0索引开始读取2个]limit==>从0索引开始 [0,N-1]      
select * from table limit 2,1;                
-- 含义是跳过2条取出1条数据,limit后面是从第2条开始读,读取1条信息,即读取第3条数据
 
select * from table limit 2 offset 1;     
-- 含义是从第1条(不包括)数据开始取出2条数据,limit后面跟的是2条数据,offset后面是从第1条开始读取,即读取第2,3条      

组函数: 去重 distinct() 统计总数sum() 计算个数count() 平均数avg() 最大值max() 最小数min()

多表连接: 内连接(省略默认inner) join ...on..左连接left join tableName as b on a.key ==b.key右连接right join 连接union(无重复(过滤去重))和union all(有重复[不过滤去重])

  • union 并集
  • union all(有重复)
  • oracle(SQL server)数据库
  • intersect 交集
  • minus(except) 相减(差集)

oracle

一、数据库对象:表(table) 视图(view) 序列(sequence) 索引(index) 同义词(synonym)

1.视图: 存储起来的 select 语句

create view emp_vw
as
select employee_id, last_name, salary
from employees
where department_id = 90;

select * from emp_vw;      

可以对简单视图进行 DML 操作

update emp_vw
set last_name = 'HelloKitty'
where employee_id = 100;

select * from employees
where employee_id = 100;      

1). 复杂视图

create view emp_vw2
as
select department_id, avg(salary) avg_sal
from employees
group by department_id;

select * from emp_vw2;      

复杂视图不能进行 DML 操作

update emp_vw2
set avg_sal = 10000
where department_id = 100;      

2.序列:用于生成一组有规律的数值。(通常用于为主键设置值)

create sequence emp_seq1
start with 1
increment by 1
maxvalue 10000
minvalue 1
cycle
nocache;

select emp_seq1.currval from dual;

select emp_seq1.nextval from dual;      

问题:裂缝,原因:

  • 当多个表共用同一个序列时。
  • rollback
  • 发生异常
create table emp1(
     id number(10),
     name varchar2(30)
);

insert into emp1
values(emp_seq1.nextval, '张三');

select * from emp1;      

3.索引:提高查询效率

自动创建:Oracle 会为具有唯一约束(唯一约束,主键约束)的列,自动创建索引

create table emp2(
       id number(10) primary key,
       name varchar2(30)
)      
create index emp_idx
on emp2(name);

create index emp_idx2
on emp2(id, name);      

4.同义词

create synonym d1 for departments;

select * from d1;      

5.表:

insert into ... values ...
update ... set ... where ...
delete from ... where ...