[英]mysql - SELECT AND INSERT QUERY into multiple table with conditions
I dont know it is possible or not in MySQl, but I have to import the old database table to new normalized database table. 我不知道在MySQl中是否可能,但是我必须将旧数据库表导入到新的规范化数据库表中。 I have 2 table user and user_roles in new one and the previous one only has admin
我在新表中有2个表user和user_roles,而前一个表只有admin
newdb.users Table user_id | username | password newdb.user_roles Table user_id | role_id
old database table 旧数据库表
olddb.admin Table id | username | password | user_type 1 | user1 | *** | admin 3 | user7 | *** | staff
admin role_id is 1 and staff role_id is 2 管理员role_id为1,职员role_id为2
So the new table after SQL insert should look like. 因此,SQL插入后的新表应该看起来像。
newdb.users Table user_id | username | password 1 | user1 | *** 3 | user7 | *** newdb.user_roles Table user_id | role_id 1 | 1 3 | 2
How to do this using MYSQL query. 如何使用MYSQL查询。 Thanks.
谢谢。
You should be basing this information on a roles
table: 您应该将这些信息基于
roles
表:
create table roles (
int id auto_increment primary key,
role_name varchar(255)
);
insert into roles (role_name)
select distinct user_type
from old.admin;
Then: 然后:
insert into new.users(username, password)
select distinct username, password
from old.admin;
( distinct
is not necessary if username
is not repeated in original table.) (如果在原始表中不重复
username
则不需要distinct
。)
And: 和:
insert into user_roles(user_id, role_id)
select u.id, r.id
from new.users u join
old.admin a
on u.user_name = a.user_name and
u.password = a.password join -- this condition may not be necessary
new.roles r
on a.user_type = r.role_name;
Although you can hard-code values into the query, I think it is a good idea to let the database do the work for you. 尽管您可以将值硬编码到查询中,但我认为让数据库为您完成工作是个好主意。 This approach is more general.
这种方法更为通用。
In order to insert roles from old table to new table: 为了将角色从旧表插入新表:
INSERT INTO newdb.user_roles
SELECT
id,
CASE WHEN user_type='admin' THEN 1
WHEN user_type ='staff' THEN 2 END AS role_id
FROM olddb.admin
In order to insert users from old table to new table: 为了将用户从旧表插入到新表:
INSERT INTO newdb.users
SELECT
id,
username,
password
FROM olddb.admin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.