My table has two columns: "id" (Auto Increment, Primary) and "number" (Unique). Now I want to the following:
What's the most efficient method to do this job?
Note:
Thank you!
To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.
All tables should have a primary key (multi-column primary keys are supported). DELETE operations are unsupported on tables without a primary key. Also, rows in tables without a primary key may appear in a different order on different nodes.
INSERT IGNORE INTO table (number) VALUES (42);
SELECT id FROM table WHERE number = 42;
That's probably the most efficient in MySQL. You could use a Stored Procedure to lump them up, which may or may not be slightly more efficient.
EDIT:
If you think it's going to be rare that new numbers come up, this 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 here if concurrent threads simultaneously select then insert the same number at the same time. In this case, the later insert will fail. You could recover from this by re-selecting on this error condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With