mysql - 根据ID更新表中的列并一次更新一行

标签 mysql sql sql-server-2008 oracle11g

我有两个表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/

相关文章:

mysql - 在 Microsoft Azure Database for Mysql Server 中添加另一个用户

sql - 如何找到正在使用函数的位置

c# - 查询当前日期的sql

sql - 数据库关系多对多三向混淆

php MySQL 多词搜索

MySQL的alter table查询非常慢

mysql - 将 Ruby 与通过 MAMP 安装的 MySQL 一起使用

sql - oracle 使用 REGEXP_SUBSTR(AGGREGATOR ,'[^;]+' ,1,LEVEL) 查询速度很慢

mysql - 选择每行及其列索引的最大值

sql-server-2008 - 使用 EF Code First 锁定