简体   繁体   中英

Use one table to update another SQL

I have having problems updating one table from another. I want SQL to update the rows in Employees from the data in CompanyEmployees where the two EmployeeNum fields are the same. Also if an EmployeeNum exists inside of CompanyEmployees that doesn't match one in Employees then I need a new row created in Employees I so far have tried a join for the two tables.

SELECT Employees.PhoneNum, Employees.Data, 
       CompanyEmployees.PhoneNum, CompanyEmployees.SystemData 
FROM CompanyEmployees 
INNER JOIN Employees 
ON CompanyEmployees.Employees=Techs.EmployeeNum  

I get the right column data in both tables but i doesnt update Employees . Do I need an INSERT or UPDATE somewhere?
How can I insert the whole row of data from CompanyEmployees into Employees where CompanyEmployees.EmployeeNum doesn't exist in Employees ?

I need to do this because CompanyEmployees is only a phone directory and Employees has phone numbers and more information. But CompanyEmployees has new hires inside it that are not inside Employees .

Remember RDBMS has the R for relational. They are built for relationships.
To update you Employees table with the CompanyEmployees table you could use something like the below:

INSERT INTO Employees (columns) VALUES (SELECT columns FROM CompanyEmployees) ON DUPLICATE KEY UPDATE

You probably do not even need 'Employees' as it is a superset of 'CompanyEmployees'. I would suggest looking to merge the two tables or at least move the data into a single table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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