简体   繁体   English

需要使用同一数据库中另一个表中的数据填充一个表

[英]Need to populate one table with data from another table in same database

I am trying to populate one table from another table with mysql. 我试图用mysql从另一个表填充一个表。 First table is users and the second table is technicians . 第一个表是用户,第二个表是技术人员。

Users contains : userID, surname, firstname, loginid, password, accesslevel . 用户包含:userID,surname,firstname,loginid,password,accesslevel。

Technicians contains : techID, tech_surname, tech_firstname, tech_loginid, tech_password, tech_accesslevel. 技术人员包含:techID,tech_surname,tech_firstname,tech_loginid,tech_password,tech_accesslevel。

When I add a user, I want the technicians table to populate if accesslevel=tech and users.loginid is not equal to technicians.tech_loginid. 当我添加用户时,如果accesslevel = tech并且users.loginid不等于technicians.tech_loginid,我希望技术人员表填充。

I have tried several things and the result is that either no record is added or all records in users where accesslevel=tech are added each time, giving me several duplicate records. 我已经尝试了几件事,结果是没有添加记录,或者每次都添加了accesslevel = tech的用户的所有记录,给了我几个重复的记录。

I tried this: 我试过这个:

INSERT INTO technicians (techID, tech_surname, tech_firstname, tech_loginid, tech_passwrd, tech_accesslevel)
SELECT firstname, surname, loginid, accesslevel, passwrd, tech_loginid
FROM users, technicians
WHERE accesslevel='tech' AND 'loginid!=tech_loginid'

It doesn't work and if I remove the AND statement from the WHERE clause it pushes all the records each time a new user is added with accesslevel=tech. 它不起作用,如果我从WHERE子句中删除AND语句,每次使用accesslevel = tech添加新用户时,它都会推送所有记录。

What am I doing wrong? 我究竟做错了什么? I've searched for hours for an answer. 我已经搜索了几个小时的答案。

Cheers 干杯

I think you're trying to insert those technicians that already do not exist in that table so a query would be something like this 我认为您正在尝试插入那些已经不存在于该表中的技术人员,因此查询将是这样的

INSERT INTO technicians  (techID, tech_surname, tech_firstname, tech_loginid, tech_passwrd, tech_accesslevel) 
SELECT loginid, surname, firstname, tech_loginid, passwrd, accesslevel 
FROM users 
LEFT OUTER JOIN technicians ON loginid = tech_loginid
WHERE accesslevel='tech' and tech_loginid IS null

You could try 你可以试试

    INSERT INTO technicians 
(techID, tech_surname, tech_firstname, tech_loginid, tech_passwrd, tech_accesslevel) 
    SELECT 
GetTechId(),surname, firstname, loginid , passwrd, accesslevel  FROM users u
    WHERE
NOT EXISTS (select 1 from technicians t where t.loginid=u.loginid) and 
u.accesslevel='tech'.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM