Mysql知識點整理


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

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

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

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)

如果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

 

轉載請注明來處。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM