mysql 更新一列加后缀,MySQL插入行,重复:添加后缀并重新插入

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.

解决方案

You could create a trigger that changes the value of NEW.slug before inserting it.

drop trigger if exists changeSlug;

delimiter |

CREATE TRIGGER changeSlug BEFORE INSERT ON slugs

FOR EACH ROW BEGIN

declare original_slug varchar(255);

declare slug_counter int;

set original_slug = new.slug;

set slug_counter = 1;

while exists (select true from slugs where slug = new.slug) do

set new.slug = concat(original_slug, '-', slug_counter);

set slug_counter = slug_counter + 1;

end while;

END;

|

delimiter ;

And this would be the results

mysql> insert into slugs values ("dude");

Query OK, 1 row affected (0.00 sec)

mysql> insert into slugs values ("dude");

Query OK, 1 row affected (0.00 sec)

mysql> insert into slugs values ("dude");

Query OK, 1 row affected (0.00 sec)

mysql> select * from slugs;

+--------+

| slug |

+--------+

| dude |

| dude-1 |

| dude-2 |

+--------+

3 rows in set (0.00 sec)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值