2019年11月27日
目錄
題目:180. 連續出現的數字
解題1:利用用戶變量實現對連續出現的值進行計數
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;
- 使用中間表(一列是數字,一列是遞增次數,使用case .. end .. )
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
;
- distinct 過濾掉Num列
解題2:使用自連接解決問題
SELECT DISTINCT a.Num as ConsecutiveNums FROM `logs` as a , `logs` as b, `logs` as c
WHERE a.id = b.Id - 1 and b.Id = c.Id - 1 and a.Num = b.Num and b.Num = c.Num;
- 利用“自連接(自身連接)“的思路,自連接(自身連接)的本質是把一張表複製出多張一模一樣的表來使用,顯而易見,效率較低
- 假如需要統計連續出現n次,豈不是要自連接n次?