简体   繁体   English

用Select插入MySQL

[英]Mysql Insert with the Select

I have two tables named employees and testdept .In employees table there are two fields as employee_id and department . 我有两个名为employeestestdept表。在employees表中有两个字段employee_iddepartment testdept table contains two fields as epfno and deptid . testdept表包含两个字段,如epfnodeptid

Now what I want to do is insert those id's from testdept table to employees table department field where employee_id matches with the epfno. 现在,我要做的是将那些ID从testdept表插入到employeesdepartment字段中, employee_id与epfno匹配。

I have tried with the below code. 我试过下面的代码。 It inserts the data as a new row. 它将数据插入为新行。 That is the problem. 那就是问题所在。

INSERT INTO employees (department)
SELECT t.deptid
FROM  testdept t, employees e
WHERE  t.epfno = e.employee_id

If I understood you correctly, you want an UPDATE statement and not an INSERT : 如果我对您的理解正确,那么您需要UPDATE语句而不是INSERT

UPDATE employees e
JOIN testdept t
 ON(e.employee_id = t.epfno)
SET e.department = t.deptid

This will update the records in employee table with the data from the corresponding row in testdept table 这将使用testdept表中相应行的数据更新employee表中的记录

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

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