K
K
koliane2017-08-22 07:24:21
MySQL
koliane, 2017-08-22 07:24:21

How to make a selection in MySQL filtering consecutive values?

There is a table "table". It has 1 column "s1". The value type is integers. There is a task: to display those lines, the values ​​of which are in a row from n number of times.
Example: there is a table. It is 1ac2e6d0452744beb95d0e927940bc9e.pngnecessary to select values ​​from it that go in a row 3 or more times. Those. The result should be the following: 3fbee6060df146e59476ab58a9b735bd.png
Tell me, how can I implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-08-22
@koliane

It is possible like this:

SELECT t2.s1
FROM (
  SELECT
    t1.id,
    t1.s1,
    IF (@max = 1, @max := t1.seq, @max := @max) AS "max1",
    IF (t1.seq = 1, @max := 1, @max := @max) AS "max2"
  FROM (
    SELECT
      (SELECT @id := @id + 1) AS "id",
      s1,
      IF (s1 = @prev + 1, @seq := @seq + 1, @seq := 1) AS "seq",
      (SELECT @prev := s1) AS "prev"
    FROM `table`,
    (SELECT @id := 0, @seq := 0, @prev := null) AS init
  ) AS t1,
  (SELECT @max := 1) AS init
  ORDER BY t1.id DESC
) AS t2
WHERE t2.max1 >= 3
ORDER BY t2.id

You can also add an additional column to the table, which will store the number of records belonging to the current series of sequential values ​​and fill / update it in the trigger when new records are inserted into the table. Then the table will look something like this:
s1 | n
 1   3
 2   3
 3   3
 7   1
12   1
22   2
23   2
 5   4
 6   4
 7   4
 8   4

And getting the necessary records will be quite trivial:
SELECT s1 FROM `table` WHERE n > 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question