For the sake of brevity, let's assume we have a numbers
table with 2 columns: id
& number
:
CREATE TABLE numbers(
id INT NOT NULL AUTO_INCREMENT,
NUMBER INT NOT NULL,
PRIMARY KEY ( id )
);
I want the number
column to auto-increment, but restart from 1 after hitting 100, satisfying the following requirements:
- If there are no records yet, set
number
to 1. - If there are already records in the table:
- If the last record's
number
is less than 100, setnumber
to that + 1. - If the last record's
number
is 100 or more, setnumber
to 1.
- If the last record's
Here's what I have so far:
INSERT INTO `numbers` (`number`)
VALUES (
IF(
IFNULL(
(SELECT `number`
FROM `numbers` as n
ORDER BY `id` DESC
LIMIT 1),
0
) > 99,
1,
IFNULL(
(SELECT `number`
FROM `numbers` as n
ORDER BY `id` DESC
LIMIT 1),
0
) + 1
)
)
This works, but uses two identical SELECT
queries.
Is there any way to remove the duplicate SELECT
?
P.S. I want to do all this within a query. No triggers or stored procedures.