Hello!
There is a table consisting of 3 columns: id (int)
, A (int)
and B(int)
. It is filled with pairs of random values A and B in the range from 0 to N inclusive, with A i ≠ B i . Then x is selected from the same range from 0 to N inclusive.
Need a query that retrieves records for which the following conditions are true:
- Or A , or B is x .
- Pair
A, B
unique among all pairs (For example, if there is(3, 1)
, then there can be no other pair(3, 1)
or(1, 3)
). - If there are several suitable pairs in the old table, then the eldest one by
id
is selected.
Examples
Source table with N = 5
:
id | A | B ---+---+--- 1 | 5 | 4 2 | 0 | 4 3 | 4 | 3 4 | 3 | 5 5 | 4 | 2 6 | 1 | 2 7 | 0 | 4 8 | 0 | 5 9 | 0 | 5 10 | 5 | 0
Sample:
when
x = 0
:id | A | B ---+---+--- 7 | 0 | 4 - был еще вариант 2 | 0 | 4, но 7 > 2 10 | 5 | 0 - был еще вариант 8 | 0 | 5 и 9 | 0 | 5, но 10 > 9 и 10 > 8
with
x = 1
:id | A | B ---+---+--- 6 | 1 | 2
with
x = 2
:id | A | B ---+---+--- 5 | 4 | 2
6 | 1 | 2
with
x = 3
:id | A | B ---+---+--- 3 | 4 | 3 4 | 3 | 5
with
x = 4
:id | A | B ---+---+--- 1 | 5 | 4 3 | 4 | 3 5 | 4 | 2 7 | 0 | 4 - был еще вариант 2 | 0 | 4, но 7 > 2
with
x = 5
:id | A | B ---+---+--- 1 | 5 | 4 4 | 3 | 5 10 | 5 | 0 - был еще вариант 8 | 0 | 5 и 9 | 0 | 5, но 10 > 9 и 10 > 8
Naturally, this can be solved within the framework of the program code, so the question is precisely in the request to MySql.