连续出现的数字。编写一个 SQL 查询,查找所有至少连续出现三次的数字。
答案是输出1,原因是1是唯一连续出现三次的数字。
DROP TABLE IF EXISTS logs;
CREATE TABLE logs (
id int(11) NOT NULL,
num int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO logs VALUES ('1', '1');
INSERT INTO logs VALUES ('2', '1');
INSERT INTO logs VALUES ('3', '1');
INSERT INTO logs VALUES ('4', '2');
INSERT INTO logs VALUES ('5', '1');
INSERT INTO logs VALUES ('6', '2');
INSERT INTO logs VALUES ('7', '2');
sql语句如下:
SELECT DISTINCT
l1.num AS ConsecutiveNums
FROM
logs l1,
logs l2,
logs l3
WHERE
l1.id = l2.id - 1
AND l2.id = l3.id - 1
AND l1.num = l2.num
AND l2.num = l3.num
执行结果如下: