用到的表和数据SQL:
CREATE TABLE leetcode.logs
(
Id int(11) NOT NULL,
Num int(11)
);
INSERT INTO leetcode.logs (Id, Num) VALUES (1, 1);
INSERT INTO leetcode.logs (Id, Num) VALUES (2, 1);
INSERT INTO leetcode.logs (Id, Num) VALUES (3, 1);
INSERT INTO leetcode.logs (Id, Num) VALUES (4, 2);
INSERT INTO leetcode.logs (Id, Num) VALUES (5, 1);
INSERT INTO leetcode.logs (Id, Num) VALUES (6, 2);
INSERT INTO leetcode.logs (Id, Num) VALUES (7, 2);
答案:
SELECT DISTINCT Num AS ConsecutiveNums
FROM (
SELECT
Num,
@count := if(@pre = Num, @count + 1, 1) AS n,
@pre := Num
FROM Logs, (SELECT
@count := 0,
@pre := 2) AS init)
AS t
WHERE t.n >= 3;
这道题给了我们一个Logs表,让我们找Num列中连续出现相同数字三次的数字,通过设置两个变量:count-记录连续出现的次数,pre-上一次比较的数字,来得到结果;
其中红框内的sql
执行结果为:
Mysql中"@"是:局部变量声明