我有两个表table1和table2,其结构如下。我需要使用表 2 中存在的值更新表 1 中的列
Table1:
ID , Txt1 , Txt2
ID 为 id ,Txt 1 和 Txt 2 为 varhr
Table 2
TableId, Id_in_table1 , ValueType , Value
TableId 是数据有效的表的 ID。因此在这种情况下 tableId 将包含 Table1 的表 id 。该表的 id 存储在另一个表中。我们基本上还需要根据此 tableId 过滤数据,因为我们需要确保我们不会复制对此表无效的数据。
现在我需要做的是,根据以下逻辑从表 2 更新表 1 的 Txt1 和 Txt2,
表 2 中的表 ID 应与“表 1”的表 ID 匹配 对于 table1 的每个 Id 等于 table2 的“Id_in_table1”, 根据table2.ValueType,将table1.value中的数据放入Txt1或Txt2中。 如果 ValueType 等于“Type1”,则更新 table1.txt1 = table2.value 否则如果 ValueType 等于“Type2”则更新 table2.txt2 = table2.value
可能还有其他可能的值类型,但在这种情况下我们不需要做任何事情。
我写的SQL查询如下:
update
table1
set
table1.txt1 = (select value from table1 c join table2 f ON c.ID = f.Id_in_table1 and f.ValueType ='Type1')
我正在考虑在两个单独的查询中更新 txt1 和 txt2。
但是这个查询将以相同的值更新 table1 中的所有行。我需要的逻辑是它应该只添加到 table2 中存在 ID 的那些行。
当 select 语句从连接返回两行时,即如果 table2 中存在两个 table1.Id,此查询也会失败。
任何人都可以帮我解决这个场景的查询吗?
PS:我需要编写一个通用查询,而不是任何数据库特定查询。
TIA
最佳答案
对于Type1
可以使用如下
update c
set c.txt1 = f.value
from table1 c
inner join table2 f
on c.ID = f.Id_in_table1
and f.ValueType ='Type1'
对于Type2
可以使用如下
update c
set c.txt2 = f.value
from table1 c
inner join table2 f
on c.ID = f.Id_in_table1
and f.ValueType ='Type2'
关于mysql - 根据ID更新表中的列并一次更新一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270565/