假定業(yè)務(wù):
查看在職員工的薪資的第二名的員工信息
創(chuàng)建數(shù)據(jù)庫(kù)
drop database if exists emps;
create database emps;
use emps;
create table employees(
empId int primary key,-- 員工編號(hào)
gender char(1) NOT NULL, -- 員工性別
hire_date date NOT NULL -- 員工入職時(shí)間
);
create table salaries(
empId int primary key,
salary double -- 員工薪資
);
INSERT INTO employees VALUES(10001,'M','1986-06-26');
INSERT INTO employees VALUES(10002,'F','1985-11-21');
INSERT INTO employees VALUES(10003,'M','1986-08-28');
INSERT INTO employees VALUES(10004,'M','1986-12-01');
INSERT INTO salaries VALUES(10001,88958);
INSERT INTO salaries VALUES(10002,72527);
INSERT INTO salaries VALUES(10003,43311);
INSERT INTO salaries VALUES(10004,74057);
題解思路
1、(基礎(chǔ)解法)
先查出salaries表中最高薪資,再以此為條件查出第二高的工資
查詢語(yǔ)句如下:
select
E.empId,E.gender,E.hire_date,S.salary
from
employees E join salaries S
on
E.empId = S.empId
where
S.salary=
(
select max(salary)from salaries
where
salary
(select max(salary) from salaries)
);
-- ---------------查詢結(jié)果------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+
2、(自聯(lián)結(jié)查詢)
先對(duì)salaries進(jìn)行自聯(lián)結(jié)查詢,當(dāng)s1=s2鏈接并以s1.salary分組,此時(shí)count的值,即薪資比他高的人數(shù),用having篩選count=2 的人,就可以得到第二高的薪資了;
查詢語(yǔ)句如下:
select
E.empId,E.gender,E.hire_date,S.salary
from
employees E join salaries S
on
E.empId = S.empId
where S.salary=
(
select
s1.salary
from
salaries s1 join salaries s2
on
s1.salary = s2.salary
group by
s1.salary
having
count(distinct s2.salary) = 2
);
-- ---------------查詢結(jié)果------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+
3、(自聯(lián)結(jié)查詢優(yōu)化版)
原理和2相同,但是代碼精簡(jiǎn)了很多,上面兩種是為了引出最后這種方法,在很多時(shí)候group by和order by都有其局限性,對(duì)于俺們初學(xué)者掌握這種實(shí)用性較廣的思路,還是很有意義的。
select
E.empId,E.gender,E.hire_date,S.salary
from
employees E join salaries S
on
S.empId =E.empId
where
(select count(1) from salaries where salary>=S.salary)=2;
-- ---------------查詢結(jié)果------------ --
+-------+--------+------------+--------+
| empId | gender | hire_date | salary |
+-------+--------+------------+--------+
| 10004 | M | 1986-12-01 | 74057 |
+-------+--------+------------+--------+
初淺總結(jié),如有錯(cuò)誤,還望指正。
總結(jié)
到此這篇關(guān)于MySQL不使用order by實(shí)現(xiàn)排名的三種思路的文章就介紹到這了,更多相關(guān)MySQL不用order by排名內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- MySQL Order by 語(yǔ)句用法與優(yōu)化詳解
- 深入解析mysql中order by與group by的順序問(wèn)題
- MySQL中union和order by同時(shí)使用的實(shí)現(xiàn)方法
- MySQL Order By語(yǔ)法介紹
- MySQL Order By索引優(yōu)化方法
- MySQL order by性能優(yōu)化方法實(shí)例
- MySQL中Order By多字段排序規(guī)則代碼示例
- 詳談mysql order by in 的字符順序(推薦)
- MySQL ORDER BY 的實(shí)現(xiàn)分析
- MySQL Order By Rand()效率分析