My question is rather complex, but I thought I should give it a try.
In short, I want to insert a row with a slug
(short string with alphas and a dash: this-is-a-slug). The problem is that slug
is a unique key and there might be duplicates.
When there is a duplicate it should be inserted with a modified slug
, like with a suffix: this-is-a-slug-1, if that fails increase the suffix: this-is-a-slug-2.
Here's the tricky part, it should be accomplished in MySQL (no PHP involved) and preferably in a INSERT statement (no variables, procedures etc.)
I've tried a simple solution like so:
INSERT INTO table (slug) VALUES(IF((SELECT COUNT(slug) FROM table WHERE slug = 'this-is-a-slug') > 0, 'this-is-a-slug-1', 'this-is-a-slug');
This should insert this-is-a-slug-1
if this-is-a-slug
exists, or this-is-a-slug
otherwise.
Expectedly, however, this spawns an error telling me that I cannot you a FROM
statement in an UPDATE
statement, or something like that.
That's the problem, hope anyone can say something about it.
P.S.: This is being used in a really heave RSS news update procedure, in which I can easily check the slug in the db with php and then modify it, but that doubles the time of my script :|, so I thought I could make it hard for mysql rather than php.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…