我目前在一个包含employee_names的表中有一列。从那时起,我创建了一个包含员工信息的表,并希望将employee_names列替换为employee_id列,该列对应于表中已有的值。
似乎是一个相当基本的问题,但似乎无法在任何地方找到答案。
编辑:添加表格结构
Responsible_table:
category_name,
employee_name (Has duplicates)
Employee_table:
employee_id {PK},
employee_name,
employee_address,
etc.
此外,如果有人可以帮助如何为Responsible_table中的每个employee_name生成具有唯一ID的employee表,那将是非常好的
答案 0 :(得分:0)
这是我的方法:
http://sqlfiddle.com/#!9/2eb74
在那个小提琴中,您可以使用数据,帮助大量尝试...首先单击左下方的“构建架构”按钮,然后尝试右侧的“运行SQL”按钮。
以上是小提琴的内容:
设置一些测试数据:
CREATE TABLE responsible (
category VARCHAR(100),
name VARCHAR(255)
);
INSERT INTO responsible VALUES
('teaching', 'First PersonA'),
('cleaning', 'Second PersonB'),
('watch', 'Third PersonC'),
('sleep', 'Fourth PersonD'),
('shopping', 'Third PersonC');
CREATE TABLE employee (
id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(100),
address VARCHAR(255),
PRIMARY KEY k_employee_id(id)
);
INSERT INTO employee VALUES
(NULL, 'First PersonA', 'some address'),
(NULL, 'Second PersonB', 'some address'),
(NULL, 'Some Person', 'some address'),
(NULL, 'Third PersonC', 'some address'),
(NULL, 'Other Person', 'some address'),
(NULL, 'Fourth PersonD', 'some address');
模式的实际转换:
ALTER TABLE responsible ADD COLUMN id INT;
UPDATE responsible r LEFT JOIN employee e ON (r.name=e.name) SET r.id=e.id;
ALTER TABLE responsible MODIFY COLUMN id INT NOT NULL;
ALTER TABLE responsible ADD FOREIGN KEY(id) REFERENCES employee(id) ON DELETE CASCADE;
ALTER TABLE responsible DROP COLUMN name;
最后的测试声明作为上述证明:
SELECT * FROM responsible;
首先向表id
添加responsible
列,然后由加入UPDATE
表的以下employee
语句填充该列。剩下的就是修改现在填充的responsible.id
列,因为它有意义,并删除现在已过时的列responsible.name
列。
答案 1 :(得分:0)
我建议你:
employee_id
删除旧列employee_name
ALTER TABLE Responsible_table ADD COLUMN employee_id INT;
UPDATE Responsible_table rt INNER JOIN Employee_table et ON rt.employee_name = et.employee_name SET rt.employee_id = et.employee_id;
ALTER TABLE Responsible_table DROP COLUMN employee_name;
至于填充表格Employee_table
:
填充
CREATE TABLE Employee_table( employee_id INT AUTO_INCREMENT, employee_name VARCHAR(32), PRIMARY KEY(employee_id) )ENGINE = MyISAM;
INSERT INTO Employee_table(employee_name)SELECT DISTINCT employee_name FROM Responsible_table;