INSERT IGNORE INTO table (number) VALUES (42); SELECT id FROM table WHERE number = 42;
This is probably the most efficient in MySQL. You can use a stored procedure to break them down, which may or may not be a bit more efficient.
EDIT:
If you think that new numbers will rarely appear, it will be even faster:
SELECT id FROM table WHERE number = 42; if (!id) { INSERT INTO table WHERE number = 42; id = SELECT @LAST_INSERT_ID; }
There is a possible race condition if simultaneous simultaneous streams simultaneously insert the same number. In this case, later insertion will not be performed. You can restore this by reselecting this error condition.
Chris
source share