I have a mysql table in which there is a column e.g. called name. The column data has a specific pattern nameBase+number. E.g.
name
----------
test0
test1
test2
stack0
stack1
stack2
Each time I want to add data to the column, I have to find the last number for specific nambeBase and add the new entry +number+1.
For example, if now test came, I have to add test3 to db.
My question: What is the best way to 1. check if the nameBase already exists in db(sth like contains) and 2.find the last nameBase number. E.g. here for test is 3.
Update : Everyone, one update. I finally used java Pattern class. So cool and easy. It made everything so simple. I just could add the /d to pattern and then I could check if that matches the name and could use the pattern group to easily access the second part.
The real solution here is to change the database schema to split this into two columns, the name and its number. It becomes trivial then to get the aggregate
MAX()viaHowever,if changing it is not an option, I would recommend using
REPLACE()to remove the name portion from the column value leaving only the number portion when querying, and get the aggregateMAX()of that to find the highest existing number for it:Or instead of
LIKE, using a regular expression, which is more accurate thanLIKE(in case a name contains another name, theLIKEmight match) but more expensive: