題目mysql
Codesql
SELECT FirstName, LastName, City, State FROM Person LEFT JOIN Address --因爲須要Person表的全部信息,因此使用左聯結 ON Person.PersonId = Address.PersonId;
on和where的區別:數據庫
數據庫在經過鏈接兩張或多張表來返回記錄時,都會生成一張中間的臨時表,而後再將這張臨時表返回給用戶。 在使用left join時,on和where條件的區別以下:函數
一、on條件是在生成臨時表時使用的條件,它無論on中的條件是否爲真,都會返回左邊表中的記錄。3d
二、where條件是在臨時表生成好後,再對臨時表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不爲真的就所有過濾掉。code
題目blog
code排序
SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary;
要建立一個新表,存儲可能只有一行的數據get
LIMIT和LIMIT OFFSET的區別產品
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條
題目
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN SET n = N-1; RETURN ( # Write your MySQL query statement below. SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT n,1 ); END
SELECT s1.Score, COUNT(DISTINCT(s2.score)) RANK From Scores s1, Scores s2 WHERE s1.score <= s2.score GROUP BY s1.Id ORDER BY Rank;
窗口函數:
<窗口函數> OVER ([partition by <列清單>] ORDER BY <排序用列清單>)
好比,按照產品類型(product_type)分類,在每一個分類中按照價格(sale_price)排序,並將排序結果寫入新列ranking中。
SELECT product_name, product_type, sale_price, RANK() OVER (PARTITION BY product_type ORDER BY sale_price) AS ranking FROM Product;
題目
代碼
case when
SELECT DISTINCT Num AS ConsecutiveNums FROM ( SELECT Num, CASE WHEN @prev = Num then @count := @count+1 WHEN (@prev := Num) is not null then @count := 1 END AS CNT FROM Logs, (SELECT @prev := null, @count := null) as t ) AS temp WHERE temp.CNT >= 3;
方法一:建立兩個虛擬表
代碼
SELECT A.Name as Employee FROM Employee A, Employee B WHERE A.ManagerId = B.Id AND A.Salary > B.Salary;
方法二:自聯結
代碼
SELECT A.Name AS Employee FROM Employee A JOIN Employee B ON A.ManagerId = B.Id AND A.Salary > B.Salary;
題目
Code
SELECT Email FROM Person GROUP BY Email HAVING COUNT(Email) > 1;