我有两张表是这样设计的。
CREATE TABLE employee
(
id INT PRIMARY KEY,
name VARCHAR(200)
);
CREATE TABLE job
(
id INT PRIMARY KEY,
name VARCHAR(200),
emp_id INT,
FOREIGN KEY (emp_id) REFERENCES employee(id)
);
insert into employee (id, name) values (1, 'user1');
insert into employee (id, name) values (2, 'user2');
insert into employee (id, name) values (3, 'user3');
insert into job (id, name, emp_id) values (1, 'job1', 1);
insert into job (id, name, emp_id) values (2, 'job2', 2);
insert into job (id, name, emp_id) values (3, 'job3', 3);
insert into job (id, name, emp_id) values (4, 'job3', 3);
我需要的是 查询 将user1,2,3复制到4,5,6中,但同时,用户1,2,3引用的一组旧作业1,2,3,4将被复制为作业5,6,7, 8和新用户4,5,6将参考新的5,6,7,8。
所以查询前的结果。
Job Table:
id name emp_id
1 t_job1 1
2 t_job2 2
3 t_job3 3
4 t_job3 3
Employee table:
id name
1 user1
2 user2
3 user3
运行查询以复制user1,2,3:
Job Table:
id name emp_id
1 t_job1 1
2 t_job2 2
3 t_job3 3
4 t_job3 3
5 t_job1 4
6 t_job2 5
7 t_job3 6
8 t_job3 6
Employee table:
id name
1 user1
2 user2
3 user3
4 user1
5 user2
6 user3
这是一个理想的案例,但在我们真正开展工作的代码中,有无限量的工作和员工关系。
那么如何通过查询来实现呢? 首先,我不能改变表结构,如果可以的话,我愿意。
附上链接: http://sqlfiddle.com/#!9/de15f/1
我们正在使用oracle,但我把这个例子放在MySQL下。
答案 0 :(得分:0)
如上所述,答案可能取决于正在使用的数据库系统。下面提到的是为SQL Server构建的工作代码。希望这可以帮助。 : - )
DECLARE @NewEmployee AS TABLE (id INT, [name] VARCHAR(200));
DECLARE @NewJob AS TABLE (id INT, [name] VARCHAR(200), emp_id INT);
DECLARE @Max INT, @i INT = 0;
INSERT INTO @NewEmployee (id, [name])
SELECT e.id + m.MaxId, e.[name]
FROM employee e
CROSS APPLY(SELECT max(id) MaxId FROM employee) m;
INSERT @NewJob (id, [name])
SELECT J.id + m.MaxId id, J.[name]
FROM job j
CROSS APPLY(SELECT max(id) MaxId FROM job) m;
SELECT @Max = MAX(id), @i = MAX(id) - COUNT(1) + 1 FROM @NewJob;
WHILE @i <= @Max
BEGIN
UPDATE nj
SET nj.emp_id = ISNULL(ne.id, me.id)
FROM @NewJob nj
CROSS APPLY (SELECT MIN(id) id FROM
( SELECT e.id id FROM @NewEmployee e
EXCEPT
SELECT emp_id id FROM @NewJob) T) ne
CROSS APPLY (SELECT MAX(e.id) id FROM @NewEmployee e) me
WHERE nj.id = @i
SET @i = @i + 1;
END;
INSERT INTO employee
SELECT * FROM @NewEmployee;
INSERT INTO job
SELECT * FROM @NewJob;
SELECT * FROM employee;
SELECT * FROM job;