简体   繁体   English

sql查询更新表,其中缺少另一个表中的字段

[英]sql query update table with missing fields from another table

I have an issue with a SQL query/SP where I'm trying to update a table that has missing data in specific fields from another table where the data in those same fields exists and is valid. 我在SQL查询/ SP中遇到问题,在该问题中,我尝试更新另一个表中特定字段中缺少数据的表,而另一个表中存在相同字段且有效的数据。 The trick here is I would like to anchor on a value in the first table. 这里的技巧是我想锚定第一个表中的值。 I can make it work with a INSERT INTO / SELECT FROM combo, but it creates a duplicate record. 我可以使其与INSERT INTO / SELECT FROM组合一起使用,但是会创建重复记录。

Im using mysql 5.x. 我正在使用mysql 5.x. Here are the details. 这是详细信息。 The table with missing data is thisweek and the table with valid data is lastweek . 数据丢失的表是thisweek ,数据有效的表是lastweek Field 1 is MACAddress (which exists and is the anchor) and exists in both tables (for ex. BE:EF:BA:BE:CA:FE), Fields 2-10 in thisweek are blank (''), but there is data in those same fields(Fields2-10) in table lastweek . 字段1是MACAddress (存在并且是锚点)并且在两个表中都存在(例如BE:EF:BA:BE:CA:FE), thisweek字段2-10为空白(''),但是上周表中相同字段(字段2-10)中的lastweek

UPDATE thisweek
SET thisweek.field2 = lastweek.field2
where thisweek.MACAddress = lastweek.MACAddress and thisweek.filed2 = ''; 

I know that query isn't anywhere close, so looking for help. 我知道查询还没有结束,因此需要帮助。 Again, the same MACAddress exists in both tables, with the only difference between tables being that field2 in thisweek is blank (and it shouldn't be) and needs to be equal to lastweek.field2 for that MACAddress . 同样,两个表中都存在相同的MACAddress ,两个表之间的唯一区别是thisweek field2为空白(并且不应为空),并且该MACAddress必须等于lastweek.field2

Thanks all. 谢谢大家

you need to JOIN thisweek and lastweek tables. 您需要加入本周表和上周表。

UPDATE thisweek
JOIN lastweek
ON thisweek.MACAddress = lastweek.MACAddress
AND thisweek.field2 =''
SET thisweek.field2 = lastweek.field2

I think you want the following: 我认为您需要以下条件:

UPDATE tw 
  SET tw.Field2 = lw.Field2
FROM
  ThisWeek tw 
  JOIN LastWeek lw ON tw.MACAddress = lw.MACAddress
WHERE
  tw.Field2 = ''
update table1 
inner join table2 on table1.id = table2.id and (table1.name = '' or table1.name is null) 
set table1.name = table2.name;

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

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