天天看點

#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 ...