If we consider the following table:
CREATE TABLE `products` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`code` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
)
With the following records:
+----+-----------+------+
| id | name | code |
+----+-----------+------+
| 1 | produto 1 | 1 |
+----+-----------+------+
| 2 | produto 2 | 2 |
+----+-----------+------+
| 3 | produto 3 | 4 |
+----+-----------+------+
| 4 | produto 4 | 6 |
+----+-----------+------+
That is, the smallest code available will be 3. To get it, we do:
SELECT min(products.code + 1) AS code FROM products
LEFT JOIN products AS temp ON products.code + 1 = temp.code
WHERE temp.code IS NULL;
That is, select the smallest value of the incremented code in 1 of a product that does not have a registered code adjacent to it. For example, without using the function min
, the returned values would be 3, 5, 7, because the code product 2 does not have an adjacent product in 3, the code product 4 does not have an adjacent product in 5 and the code product 6 does not have a product in 7. As the returned value is incremented in 1, it would be 2+1, 4+1, 6+1. Using the function min
, We return only the smallest of them: 3.
| code |
|------|
| 3 |
See working on Sqlfiddle.
If a record is added with code 3:
+----+-----------+------+
| id | name | code |
+----+-----------+------+
| 1 | produto 1 | 1 |
+----+-----------+------+
| 2 | produto 2 | 2 |
+----+-----------+------+
| 3 | produto 3 | 4 |
+----+-----------+------+
| 4 | produto 4 | 6 |
+----+-----------+------+
| 5 | produto 5 | 3 |
+----+-----------+------+
The result of the same consultation shall be:
| code |
|------|
| 5 |
See working on Sqlfiddle.
Regardless of the information... I would just like a query that returns, in this case, the number 3, because it is the next of the order that was skipped. For example, in the database I have 5 records, with the following codes: 1,2,3,6,7. In this case, I would like a query q return the number 4.
– Cristian