2011-04-15 87 views
9

兩個表。SQL根據另一個表中的條件更新一個表

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

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

這兩個表具有相同的主鍵數據(topic_id)。

我需要用文字來更新數據字段(內容表)「已禁用」,但只有在CONTENT_TYPE場(主題表)=文本「裂谷熱」

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

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

但我怎麼能把這些放在一起。

回答

19

標準的ANSI SQL解決方案(應該在任何DBMS上工作)

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

謝謝你,工作完美。這是SQlite,忘記提及這一點。 – 2011-04-15 22:48:09

6

這應該如果您正在使用SQL Server

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

您還可以通過做這樣的更新與主題價值的內容合作:

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

不知道這是否適用於這種案例,但它是很好的知道你可以...

+0

是不是缺少'content_type ='rvf''的條件 – 2011-04-15 22:30:34

+0

是的,已更新。謝謝:) – 2011-04-15 22:31:52

相關問題