MySQL插入行,重复:添加后缀并重新插入
我的问题相当复杂,但我想我应该尝试一下。
简而言之,我想插入一行带有 slug
(带有字母和破折号的短字符串:this-is-a-slug)。问题是 slug
是一个唯一的键,并且可能存在重复项。
当存在重复项时,应使用修改后的 slug
插入,例如使用后缀:this-is-a-slug-1,如果失败,请增加后缀:this-is-a-slug -2。
这是棘手的部分,它应该在 MySQL 中完成(不涉及 PHP),最好是在 INSERT 语句中完成(没有变量、过程等)。
我尝试过一个简单的解决方案,如下所示:
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-is-如果
,否则 this-is-a-slug
存在,则为 a-slug-1this-is-a-slug
存在。
然而,预计这会产生一个错误,告诉我我不能在 UPDATE
语句中使用 FROM
语句,或者类似的东西。
这就是问题所在,希望大家能说说。
PS:这是在一个真正的RSS新闻更新程序中使用的,在这个程序中,我可以轻松地用php检查数据库中的slug,然后修改它,但这使我的脚本时间加倍:|,所以我想我可以使mysql 比 php 更难。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个触发器来更改 NEW 的值.slug 在插入之前。
这就是结果
You could create a trigger that changes the value of NEW.slug before inserting it.
And this would be the results