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. First table is users and the second table is technicians .
Users contains : userID, surname, firstname, loginid, password, accesslevel .
Technicians contains : 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 techn开发者_开发技巧icians.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.
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.
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'.
精彩评论