SQL 根据另一个表中的条件更新一个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5682936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:10:55  来源:igfitidea点击:

SQL Update one table based on conditions in another table

sqlsql-update

提问by Josh Bond

Two tables.

两张桌子。

Content (table),
   topic_id (primary key),
   data (text)

Topics (table),
   topic_id (primary key),
   content_type (text)

Both tables have the same primary key data (topic_id).

两个表具有相同的主键数据(topic_id)。

I need to update the data field (Content table) with the text "disabled" but only where the content_type field (Topics table) = the text "rvf"

我需要使用文本“禁用”更新数据字段(内容表),但仅当 content_type 字段(主题表)= 文本“rvf”

I can: SELECT * from topics WHERE content_type = "rvf";

我可以: SELECT * from topics WHERE content_type = "rvf";

I can: UPDATE content SET data = ("disabled");

我可以: UPDATE content SET data = ("disabled");

But how can I put those together.

但是我怎么能把它们放在一起。

回答by a_horse_with_no_name

Standard ANSI SQL solution (should work on any DBMS)

标准 ANSI SQL 解决方案(应该适用于任何 DBMS)

UPDATE content 
   SET data = 'disabled'
 WHERE topic_id IN (SELECT t.topic_id 
                    FROM topics t
                    WHERE t.content_type = 'rvf')

回答by Abe Miessler

This should work if you are using SQL Server

如果您使用的是 SQL Server,这应该可以工作

UPDATE content 
SET data = 'disabled'
FROM content
INNER JOIN topics
on content.topic_id = topics.topic_id
WHERE content_type = 'rvf'

You can also update content with a value from topics by doing something like this:

您还可以通过执行以下操作使用主题中的值更新内容:

UPDATE content 
SET content.data = topics.content_type
FROM content
INNER JOIN topics
on content.topic_id = topics.topic_id
WHERE content_type = 'rvf'

Not sure if it applies in this case, but it's good to know you can...

不确定它是否适用于这种情况,但很高兴知道您可以...