MySQL query for 3 consecutive integers between records

MySQL

Given a table where each record has a year integer value, how do I query to see if there are 3 or more consecutive years?

| id | year |
+----+------+
| 1  | 1990 |
| 1  | 1991 |
| 1  | 1992 |
| 2  | 1973 |
| 3  | 1993 |
| 3  | 1994 |
| 3  | 1995 |
| 3  | 1996 |

Given the above table, the resulting records returned by the query would be:

| id |
+----+
| 1  |
| 3  |

The query would return ids 1 and 3 since those two records contain have consecutive years. How would I write such a query?

Best Answer

SELECT DISTINCT
t.id
FROM tablename t
WHERE EXISTS (
    SELECT 1 FROM tablename x
    WHERE x.id = t.id
    AND x.year = t.year+1
)
AND EXISTS (
    SELECT 1 FROM tablename x
    WHERE x.id = t.id
    AND x.year = t.year-1
)