简体   繁体   English

当 ID 匹配时,我需要将第二个表中的值插入到第一个表中

[英]I need to insert the values from the second table to the first table whenewer the ID matches

I have 2 tables.我有 2 张桌子。 Below is the fields description.以下是字段说明。 1st table Fields: EmployeeID, Name, EmployeeStatus, PreferredName第一个表字段:EmployeeID、Name、EmployeeStatus、PreferredName

2nd table Fields: EmployeeID, PreferredName第二个表字段:EmployeeID,PreferredName

I need to insert the values of PreferredName from 2nd table to the first table whenever EmployeeID matches.每当 EmployeeID 匹配时,我需要将第二个表中的 PreferredName 值插入到第一个表中。 Currently all values of PreferredName in the 1st table are null.目前第一张表中所有 PreferredName 的值都是 null。 If no match by EmployeeID they should remain null.如果 EmployeeID 不匹配,则它们应保留为 null。 This is SQL Server.这是 SQL 服务器。

I am trying something like:我正在尝试类似的东西:

insert into  [Table1] PreferredName  values 

SELECT  
      [PreferredName]

  FROM [Table2]
  where [EmployeeID] in (SELECT  EmployeeID FROM [Table1]

I think you actually want to UPDATE the table, not INSERT new data.我认为您实际上想要UPDATE表,而不是INSERT新数据。 For that, you can use an UPDATE with JOIN query:为此,您可以使用UPDATEJOIN查询:

UPDATE table1
SET table1.PreferredName = table2.PreferredName
FROM table1
JOIN table2 ON table2.EmployeeID = table1.EmployeeID

Demo on dbfiddle dbfiddle 上的演示

you can use not exists keyword你可以使用not exists关键字

insert into table1 (preferredname) 
select t2.preferredname
from table2 t1 where
    not exists (select 1 from table1 t1 where t1.preferredname = t2.preferredname)

暂无
暂无

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

相关问题 MySQL 如果 table1.id = table2.table1_id 查询应该在第一个表中插入第二个表 - MySQL Query should insert a second table into the first table if table1.id = table2.table1_id VBA-插入两个表,其中第一个表的id是第二个字段 - VBA - Insert in two table where id from first table is a field in second SQL 从第一个表中插入第二个表值,pk=fk 不起作用 - SQL Insert into second table values from first table with pk=fk not working 比较两个表中的值,并将从第一个表中获取的值插入第二个表中 - Compare the values in two tables and insert into the second table the value fetched from the first table 从与第一个表中的值匹配的另一个表中返回值 - Return value from another table that matches values from the first table 我想将第一个SQL表中的数据插入第二个SQL表中,而第二个表中不存在额外的列 - I want to insert data from first SQL table into second one also with an extra column not present in the second one 如果id匹配,SQL从第二个表中选择日期 - SQL Select date from second table if id matches mysql从第一个表中的列更新第二个表中列的行,其中第一个表中的另一列与第二个表中的列匹配 - mysql update rows of column in second table from column in first table where another column in first table matches column in second table 计算第二个表中与第一个表中的ID相匹配的条目 - Count entries from second Table that match id from first Table 如何在两个表中插入其他值的同时,根据两个表中的userid将第一个表中的用户名插入第二个表中 - how to insert user name from first table into second table based on userid from both tables whle inserting other values into table2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM