K
K
koliane2018-05-31 15:01:34
MySQL
koliane, 2018-05-31 15:01:34

How to compose the following SQL query?

The initial selection is sorted in ascending order by ID_1 and ID_2.
ID_2 is always greater than ID_1.
92a76af420.jpg
It is necessary to obtain such a selection, where the ID_2 of one record will be less than the ID_1 of the next record.
That is, for the above selection, the result will be the following: 7bd4686f54.jpg
How to create such a query and is it possible (on PostgreSql or MySql)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2018-05-31
@koliane

For a primitive case, we always select the first available entry:

SET @last = 0;
SELECT `ID_1`, @last := `ID_2` AS `ID_2`
  FROM (
    SELECT `ID_1`, `ID_2` 
      FROM `table`
      ORDER BY `ID_1`, `ID_2`
  ) AS `t`
  WHERE `ID_1` > @last;

M
Melkij, 2018-05-31
@melkij

Look into window functions. lag and lead, in postgresql for a long time, finally appeared in mysql in 8.0. For older mysql - pervert.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question