修改数据然后插入,如果它已经存在已经使用mysql

时间:2015-08-29 07:33:55

标签: php mysql

我正在使用mysql和PHP。

我有一张像

这样的表格
name    age     department
----    ---     ----------
aaa     10      1
bbb     25      1
ccc     25      2

当我插入 name = aaa 的下一行时,我需要将其存储为 aaa(1)

再次插入一行 name = aaa 时,我需要将其存储为 aaa(2)

结果应该是

name    age     department
----    ---     ----------
aaa     10      1
bbb     25      1
ccc     25      2
aaa(1)  36      2
aaa(2)  27      3

是否可以通过mysql实现?

如果需要,我们还可以创建更多列。

2 个答案:

答案 0 :(得分:2)

drop table if exists t1;
create table t1 (name text,   age int,      department int);
insert into t1 values
("aaa", 10, 1),
("aaa(1)", 10, 1),
("bbb", 25, 1),
("ccc", 25, 2);

insert into t1 values(
  (select if(c, concat(name, "(", c, ')'), name) from 
    (select n.name, count(*) c from 
      (select @n:="aaa" name) n 
      join 
      (select name from t1) t 
      on t.name=n.name or t.name like concat(n.name, '(%')) ttt), 
  1, 1);

select * from t1

Demo on sqlfiddle

答案 1 :(得分:0)

在MySQL中它可能是这样的:

INSERT INTO `staff` SELECT concat('aaa',count(*)) as name, '36' as age,'2' as department FROM `staff` WHERE name='aaa'