根据MySQl中的Count更新重复列值

时间:2013-12-02 19:54:47

标签: mysql

我有这样的表

Employeeid  Name   CompanyID
1           Achal      1
2           Anil       1
3           Anil       1
4           Sachi      2
5           Anil       2
6           Sachi      1
7           Sachi      2

如果同一家公司有多名员工,我想更新员工的姓名

我的结果表应该是这样的

Employeeid  Name   CompanyID
1           Achal      1
2           Anil(1)    1
3           Anil(2)    1
4           Sachi(1)   2
5           Anil       2
6           Sachi      1
7           Sachi(2)   2

我的查询是这样的

Update tblemplayee emp 
join 
(
  select sname,count(*) 
  from tblemployee 
  group by sname,companyid
) innertable 
  on innertable.employeeid=emp.employeeid 
set sname = concat(sname,'(', ,')') .

如何更改查询以获得结果。

1 个答案:

答案 0 :(得分:1)

如果您只需执行一次查询,则可以使用此查询:

UPDATE
  employees INNER JOIN (
    SELECT e1.Employeeid, COUNT(e2.Employeeid) n
    FROM
      employees e1 INNER JOIN employees e2
      ON e1.Name=e2.Name
         AND e1.CompanyID=e2.CompanyID
         AND e1.Employeeid>=e2.Employeeid
      INNER JOIN (SELECT Name, CompanyID
                  FROM employees
                  GROUP BY Name, CompanyID
                  HAVING COUNT(*)>1) dup
      ON e1.Name=dup.Name AND e1.CompanyID=dup.CompanyID
    GROUP BY
      e1.Employeeid, e1.Name) counts
  ON employees.Employeeid = counts.Employeeid
SET
  Name = CONCAT(Name, '(', counts.n, ')');

请参阅小提琴here