SQL query: finding a space in the primary key

How to write a single select statement that does the following:

I have an integer column in my table and I want to find the minimum available (unused) value in this column, where the value is less than 1000, and also where the value does not exist in TableB Column1

thank

+3
source share
2 answers

Like LukeH, but he does what you asked:

SELECT MIN(a.your_column) - 1 AS answer
FROM your_table AS a
LEFT JOIN your_table AS a2
        ON a2.your_column = a.your_column - 1
LEFT JOIN tableB AS b
        ON a.your_column = b.column1
WHERE a.your_column < 1000
    AND b.column1 IS NULL
    AND a2.your_column IS NULL

Edit:

UNION
SELECT MIN(a.your_column) + 1 AS answer
FROM your_table AS a
LEFT JOIN your_table AS a2
        ON a2.your_column = a.your_column + 1
LEFT JOIN tableB AS b
        ON a.your_column = b.column1
WHERE a.your_column < 1000
    AND b.column1 IS NULL
    AND a2.your_column IS NULL

And select the minimum number of two values.

- , 1, A B, A + 1 B-1, . , A + 1 , ...

+1

7, , , , .

CREATE TABLE #TableA (Value INT)
INSERT #TableA (Value) VALUES (1)
INSERT #TableA (Value) VALUES (2)
INSERT #TableA (Value) VALUES (3)
INSERT #TableA (Value) VALUES (5)
INSERT #TableA (Value) VALUES (6)
INSERT #TableA (Value) VALUES (8)

CREATE TABLE #TableB (Value INT)
INSERT #TableB (Value) VALUES (4)

SELECT    MIN(A1.Value) + 1
FROM      #TableA A1
LEFT JOIN #TableA A2 ON A2.Value = A1.Value + 1
LEFT JOIN #TableB B1 ON B1.Value = A1.Value + 1
WHERE     A2.Value IS NULL
AND       B1.Value IS NULL
AND       A1.Value < 1000

DROP TABLE #TableA
DROP TABLE #TableB
0

Source: https://habr.com/ru/post/1768195/


All Articles