《SQL CookBook》 簡單查詢彙總

    下載了《SQL CookBook》,認真專研一下,基礎是很重要的,是時候拾回那些悄悄溜走的知識了。mysql

1.       查詢結果排序sql

 

1.1    顯示部門10中的員工名字、職位和工資,並按照工資的升序排列。函數

select ename,job,sal from emp order by sal asc;spa

 

1.2    EMP表中,首先按照DEPTNO的升序排序,而後按照工資的降序排列。排序

select empno,deptno,sal,ename,job from emp order by deptno asc,sal descci

 

1.3 EMP表中返回員工名字和職位,而且按照職位字段的最後兩個字符排序。io

select ename,job from emp order by substr(job,length(job)-2);ast

 

1.3    EMP中根據COMM排序結果,處理控制排在最後。基礎

select ename,sal,comm from ( select ename,sal,comm ,case when comm is null  then 1 else 0 end as is_null from emp) x order by is_null,comm;select

 

1.4    若是JOB 是「SALESMAN,要根據COMM來排序。不然,根據SAL排序。

select ename,sal,job,comm

    -> from emp

    -> order by

    -> case when job='SALESMAN' then comm

-> else sal end;

 

2.      操做多個表

 

2.1    要顯示EMP表部門10中員工的名字和部門編號,以及DEPT表中每一個部門的名字和部門編號。

mysql> select ename as ename_and_dname,deptno from emp where deptno=10

    -> union all

    -> select line,null from t1

    -> union all

-> select dname,deptno from dept;

 

2.2    顯示部門10 中全部員工的名字,以及每一個員工所在部門的工做地點。

select ename,loc rom emp e,dept d where e.deptno = d.deptno and e.deptno = 10;

 

select ename,loc from emp e join dept d on(e.deptno=d.deptno) where e.deptno = 10; (等值內聯)

2.3    從表DEPT中查找在表EMP中不存在數據的全部部門。

mysql> select deptno

    -> from dept d

    -> where not exists

-> (select null from emp e where d.deptno=e.deptno);

 

子查詢關注的不是返回結果,而是兩個表之間的關係,因此是查詢null

1.       有對應關係,則有返回,not exists false,對於最外層查詢則無結果;

2.       沒對應關係,則無返回,not exists true,對於最外層查詢則保留不存在的結果。

 

2.4查找沒有職員的部門;

mysql> select d.*

    -> from dept d left join emp e

    -> on(d.deptno = e.deptno)

-> where e.deptno is null;

 

返回一個表中的全部行,以及另外一個表中與公共列匹配或者不匹配的行,而後保存不匹配的行。

 

2.5    返回全部員工信息、他們的工做部門地點及所得到的獎勵。

Mysql> select ename,loc,received

->from emp e join dept d on(e.deptno = d.deptno)

->left join emp_bonus eb on(e.empno = eb.empno);

 

標量子查詢(不會危及到當前結果而獲取額外數據的一種簡單方法;要求標量子查詢返回的是標量值)

mysql> select e.ename,d.loc,

    -> (select received from emp_bonus eb where eb.empno = e.empno)

    -> from emp e,dept d

    -> where e.deptno = d.deptno

-> order by 2;

 

2.6    查找在部門10中全部員工的工資合計和獎金合計。(並非全部人都有獎金)

 

考慮是否有重複工資的計算,由於獎金錶可能有一名員工有兩個獎金紀錄;

考慮部門裏是否有沒有獎金的員工,也要算入部門的總工資。

mysql> select deptno,sum(distinct sal) as total_sal,sum(bonus) as total_bonus

    -> from (

    -> select e.deptno,e.sal,e.sal*case

    -> when eb.type is null then 0

    -> when eb.type = 1 then .1

    -> when eb.type = 2 then .2

    -> else .3

    -> end as bonus

    -> from emp e left join emp_bonus eb

    -> on(e.empno = eb.empno)

-> where e.deptno = 10) x;

 

2.7    須要在表EMP中查找出全部比」WARD」 提成(COMM)低的員工,提成爲NULL的員工也應包括在其中;

coalesce()函數 [keules]

mysql> select ename,comm, coalesce(comm,0)

    -> from emp

    -> where coalesce(comm,0) < (select comm from emp where ename = 'WARD');

相關文章
相關標籤/搜索