mysql 使用增量列更新重复记录

xmq68pz9  于 2023-02-18  发布在  Mysql
关注(0)|答案(2)|浏览(173)

--创建

CREATE TABLE employee 
(
  emp_id INTEGER,
  job_code TEXT,
  cnt_check int
);

--插入

INSERT INTO employee(emp_id,job_code) VALUES (0001, 'JC001');
INSERT INTO employee(emp_id,job_code) VALUES (0001, 'JC001');
INSERT INTO employee(emp_id,job_code) VALUES (0002, 'JC002');
INSERT INTO employee(emp_id,job_code) VALUES (0002, 'JC002');
INSERT INTO employee(emp_id,job_code) VALUES (0003, 'JC003');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');

预期产出

emp_id  job_code  cnt_check
--------------------------------
0001    JC001       1
0001    JC001       2
0002    JC002       1
0002    JC002       2
0003    JC003       1
0004    JC004       1
0004    JC004       2
0004    JC004       3

我的尝试:

update employee t1
join 
(
select emp_id ,job_code ,row_number() over(partition by emp_id ,job_code ) rnk
from employee
) t2 
on t1.emp_id = t2.emp_id and t1.job_code = t2.job_code 
set t1.cnt_check = t2.rnk;

但所有记录都更新为值1。
Demo link

0g0grzrc

0g0grzrc1#

使用示例数据中的确切列,我们可以尝试:

SELECT emp_id, job_code,
       ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY emp_id) AS cnt_check
FROM employee
ORDER BY 1, 3;

请注意,我建议 * 不要 * 进行此更新,因为每次数据更改时,您可能都必须再次运行更新。

46qrfjad

46qrfjad2#

您可以使用使用BEFORE INSERT触发器和附加表的生成:

CREATE TABLE autoinc_helper (
  emp_id INT,
  cnt_check INT AUTO_INCREMENT,
  PRIMARY KEY (emp_id, cnt_check)
) ENGINE = MyISAM;
CREATE TRIGGER generate_autoinc
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
  DECLARE autoinc INT;
  INSERT INTO autoinc_helper (emp_id) VALUES (NEW.emp_id);
  SET autoinc = LAST_INSERT_ID();
  SET NEW.cnt_check = autoinc;
  DELETE FROM autoinc_helper WHERE emp_id = NEW.emp_id AND cnt_check < autoinc;
END

DEMO fiddle

相关问题