As already noted, this will work:
SELECT id, title, slug FROM news WHERE slug RLIKE '^some-really-interesting-article(-[0-9]+)?$'
However, MySQL is not smart enough to use indexes effectively with RLIKE
. (If you have an index in the slug
column, it may try to use it, but will have to perform a full index scan.) It turns out, however, that you can use the redundant LIKE
clause to help MySQL process the query more efficiently, for example:
SELECT id, title, slug FROM news WHERE slug LIKE 'some-really-interesting-article%' AND slug RLIKE '^some-really-interesting-article(-[0-9]+)?$'
A LIKE
request may coincide with some false positives, such as some-really-interesting-article-about-something-else-entirely
, but RLIKE
will supplant them. Of course, if you don't care about such false positives, you can completely eliminate RLIKE
.
Of course, another possibility would be to create a unique index in the
slug
column (which you really should have anyway) and just keep increasing the pool and trying to insert the record until
INSERT
succeeds. Of course, this also means that you should check the error code and message to find out why it fails if this happens. (If a
INSERT
fails due to a double value,
the error code should be
1062 , and
the error message should contain the name of the duplicate.)
In any case , the SQLize link is here if you want to play with the query; I left some comments in it.