简体   繁体   English

SQL-使用同一表中其他多个行的值一次更新多个行

[英]SQL - Update multiple rows at once with values from multiple other rows in the same table

I apologize in advance if this was asked already, I tried searching but couldn't find an exact match. 如果已被问到,我事先表示歉意,我尝试搜索但找不到完全匹配的内容。

Basically, I have a table that contains themes. 基本上,我有一个包含主题的表。 Use the snippet below as a rough idea of how the table is set up. 使用下面的代码片段粗略了解表格的设置方式。

theme_name  field_name  color  
'Default'   'Header'    'Orange' 
'Default'   'Footer'    'Orange'
'Default'   'Body'      'Orange'
'Newtheme   'Header'    'Red' 
'Newtheme'  'Footer'    'White'
'Newtheme'  'Body'      'Blue' 

Basically, what I need to do is write a query that updates the values in the "color" field for each row of theme_name default to match those of the corresponding values on the rows for Newtheme. 基本上,我需要做的是编写一个查询,该查询更新theme_name每行默认值“ color”字段中的值,以匹配Newtheme行中相应值的值。 In other words, it should look like this at the end: 换句话说,最后应该是这样的:

theme_name  field_name  color  
'Default'   'Header'    'Red' 
'Default'   'Footer'    'White'
'Default'   'Body'      'Blue'
'Newtheme   'Header'    'Red' 
'Newtheme'  'Footer'    'White'
'Newtheme'  'Body'      'Blue' 

Unfortunately, there is no unified ID number on the table for every row with the same theme_name, and I am unable to create one. 不幸的是,表上没有具有相同theme_name的每一行的统一ID号,我无法创建一个。

Now, each theme has a lot more rows in the real table than the example I gave. 现在,每个主题在实际表中的行都比我给出的示例多得多。 I could write use 我可以写使用

SET value=(Select value 
           from Table 
           where theme_Name='Newtheme') 
where theme_name='Default' 
  and field_name='Header'`

That would fix a single row. 那将修复一行。 Then I could repeat that update statement for each and every row. 然后,我可以为每一行重复该更新语句。 However, I suspect there's a much quicker way to do this, where I could update all of them in one single update statement. 但是,我怀疑有一种更快的方法来执行此操作,在这里我可以在一个更新语句中更新所有这些方法。 I just have no idea what it is. 我只是不知道那是什么。

Hopefully, my request makes sense. 希望我的要求是合理的。 Thank you in advance. 先感谢您。

Looks like a simple co-related UPDATE query: 看起来像一个简单的,相关的UPDATE查询:

update the_table
  set color = (select color
               from the_table t2
               where t2.theme_name = 'NewTheme'
                 and t2.field_name = the_table.field_name)
where theme_name = 'Default';

This would fail if (theme_name, field_name) is not unique however 如果(theme_name, field_name)不是唯一的,则失败

You can use self-join to do this. 您可以使用自我联接来做到这一点。 Try the following: 请尝试以下操作:

update a
set a.color = b.color
from themes a
join themes b on a.field_name = b.field_name and a.them_name <> b.theme_name
where a.theme_name = 'Default'

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

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