Mysql知識點整理

刷Leecode時遇到的MySQL知識點整理html

1. case ... when ... then ...[when ... then ...] else ... endjava

https://blog.csdn.net/helloxiaozhe/article/details/78124138sql

2. limit offset網絡

兩者一般與order by聯合使用以求取第幾大第幾小的記錄。函數

使用區別:假設要返回某一字段的第2-4大的數據性能

limit 3 offset 1 --讀取三條,從第二條開始讀。讀取數量在前,偏移量在後學習

limit 1,3 --從第二條(偏移量從0開始)開始讀,讀取三條。讀取數量在後,偏移量在前測試

 

select distinct salary from employee order by salary desc limit 3 offset 1 select distinct salary from employee order by salary desc limit 1,3 

 

 

此外,使用limit,offset能夠實現分頁查詢,pageNumber:頁碼,numberPerPage:每頁數據量優化

 

select * from table_name [過濾條件] limit pageNumber offset (pageNumber-1)*numberPerPage select * from table_name [過濾條件] limit (pageNumber-1)*numberPerPage,pageNumber 

3. IFNULL(expr1,expr2)spa

若是expr1不是NULL,IFNULL()返回expr1,不然它返回expr2。IFNULL()返回一個數字或字符串值

對於2的第一個例子,更嚴謹的寫法是(當查不到數據時返回null,參考https://leetcode-cn.com/problems/second-highest-salary),這個也是提醒咱們要考慮嚴謹。

 

select ifnull((select distinct salary from employee order by salary desc limit 1,3),null) as conSalary 

 

 4. MySQL Date 函數

http://www.w3school.com.cn/sql/sql_dates.asp

DATE_ADD(date,INTERVAL expr type) : 函數向日期添加指定的時間間隔,例date_add('2019-03-31',interval 1 day)
DATE_SUB(date,INTERVAL expr type) : 函數從日期減去指定的時間間隔,例SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 2 DAY) AS OrderPayDate FROM Orders

DATEDIFF(date1,date2) : 函數返回兩個日期之間的天數,例SELECT DATEDIFF('2008-12-30','2008-12-29') AS DiffDate 返回1,要是第一個參數小於第二個參數就返回負值
EXTRACT(unit FROM date) : 函數用於返回日期/時間的單獨部分,好比年、月、日、小時、分鐘等等。
CURTIME(): 函數返回當前的時間。
CURDATE(): 函數返回當前的日期。
NOW(): 函數返回當前的日期和時間。
DATE(date): 函數返回日期或日期/時間表達式的日期部分
DATE_FORMAT(date,format):函數用於以不一樣的格式顯示日期/時間數據。

5. join、inner join、left join、right join、full join 

參考http://www.w3school.com.cn/sql/sql_join.asp

join和inner join相同,full join至關於left join、right join查詢的並集

6.判斷字段奇偶的方式

https://blog.csdn.net/zhazhagu/article/details/80452473

7.group by,order by,having,聚合函數等做用於結果集上

8.錯誤

You can't specify target table 'person' for update in FROM clause

https://zhidao.baidu.com/question/68619324.html

不能對同一個表select的同時進行更新操做,例以下面的select t.id from就是避免對同一表操做

Every derived table must have its own alias

子查詢必須有別名,例以下面的別名t必須有

例:題目來自於https://leetcode-cn.com/problems/delete-duplicate-emails/

Unknown column 't.id' in 'field list'

min(id)默認列名就是min(id),因此要記得加別名id

 

delete from person where id not in ( select t.id from ( select min(p.id) id from person p group by p.email) t ) 

 

9.distinct c1,c2,...

過濾掉c1,c2,....都相同的數據記錄,即判斷多列同時不重複

10. and,or優化查詢

https://www.cnblogs.com/ouhouki/p/9661927.html

11.MySQL中實現rank排名查詢

https://blog.csdn.net/justry_deng/article/details/80597916

例子:https://leetcode-cn.com/problems/rank-scores/

 

 select score, convert(case when @preS = score then @curR when @preS := score then @curR := @curR+1 when @preS = 0 then @curR := @curR+1 end,unsigned integer) as rank from Scores , (select @curR:=0, @preS:=NULL ) r order by score desc --------------------------------------- SELECT Score, (SELECT count(DISTINCT score) FROM Scores WHERE score >= s.score) AS Rank FROM Scores s ORDER BY Score DESC ; 

 

 第二種性能不如第一種

12.自定義函數

https://leetcode-cn.com/problems/nth-highest-salary/

 

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN set n = n-1; RETURN ( # Write your MySQL query statement below. select t.salary from(select distinct salary from employee order by salary desc limit 1 offset n) t ); END 

 

13. case when then或者if交換座位問題

https://leetcode-cn.com/problems/exchange-seats/

 

 --------------------------------方法一---------------------------------- select t.id, case when t.id%2=0 then (select s.student from seat s where s.id = t.id-1 ) when t.id=(select max(id) from seat) then student when t.id%2=1 then (select s.student from seat s where s.id = t.id+1 ) end as student from seat t ----------------------------------方法二---------------------------------- select if(mod(id,2)=1 and id = (select count(1) from seat),id,if(mod(id,2)=1,id+1,id-1)) id,student from seat order by id ----------------------------------方法三---------------------------------- SELECT (CASE WHEN MOD(id,2) = 1 AND id = (SELECT COUNT(*) FROM seat) THEN id WHEN MOD(id,2) = 1 THEN id+1 ElSE id-1 END) AS id, student FROM seat ORDER BY id; 

 

 

 

方法二三,性能至關,if性能稍快於case(可能受網絡影響),都比第一種快了一倍,第一種由於兩個子查詢耗時。

 14. 重命名不能出如今where後面嗎

(下面會報Unknown column 'c' in 'where clause'

https://leetcode-cn.com/problems/consecutive-numbers/

 

 select num, convert(( case when @pre=num then @n:=@n+1 when @pre:=num then @n:=1 end ),unsigned int) as c from logs ,(select @n:=0,@pre:=null)r where c>=3(去掉「where c>=3」就正確了) -------------------------------------------正確答案------------------------------------------------------------------------- select distinct t.num as ConsecutiveNums from (select num, convert(( case when @pre=num then @n:=@n+1 when @pre:=num then @n:=1 end ),unsigned int) as c from logs ,(select @n:=0,@pre:=null)r)t where t.c>=3 

注意點:

①變量前的@必定不要忘帶,「:」不要忘寫

②別名c不能在當前where中使用,會報c找不到

③distinct過濾掉重複的([1,3],[1,4],[1,5],[1,6],[1,7],若是不過濾的話會輸出[1,1,1,1,1])

15.聚合函數只能select被聚合的字段以及分組字段,其餘字段查詢,會發生錯位,由於其它字段與被聚合字段和分組字段是多對一的關係。

16. 派生表關聯,多表關聯

題目來自https://leetcode-cn.com/problems/department-highest-salary/

Employee,Department 兩張表和由Employee生成的派生表,共有3張表,每張表取一個字段。必定要讓三個表互相關聯到,否則會出現數據錯亂
三表關聯where測試比join關係性能好點,不知原理爲什麼?
select d.name Department , e.name Employee, m.salary
from Employee e,Department d,
     (select max(salary) salary,departmentid from employee group by departmentid)m
where e.Salary = m.Salary and d.id=m.departmentid and e.DepartmentId =d.id
------------------
select d.name Department, e.name Employee, m.salary
from
     (select max(salary) salary,departmentid from employee group by departmentid) m
join Employee e on e.Salary = m.Salary
join Department d on d.id=m.departmentid and d.id = e.departmentid
要增強學習,作到知其然,也要知其因此然。

17.round(x,d):x保留d位小數

 

爲了獲得而努力

 

2019-04-01

 

轉載請註明來處。

相關文章
相關標籤/搜索