Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update one table based on conditions in another table

Tags:

sql

sql-update

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).

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"

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

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

But how can I put those together.

like image 754
Josh Bond Avatar asked Apr 15 '11 22:04

Josh Bond


People also ask

How do you update a column in SQL based on condition from another table?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.

How can I update data from one table to another table?

We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.

Can you write update query with WHERE condition?

Learn Python + JavaScript + Microsoft SQL for Data science The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.

How do you update values based on conditions in SQL?

Update with condition WHERE clause can be used with SQL UPDATE to add conditions while modifying records. Without using any WHERE clause, the SQL UPDATE command can change all the records for the specific columns of the table.


2 Answers

Standard ANSI SQL solution (should work on any DBMS)

UPDATE content 
   SET data = 'disabled'
 WHERE topic_id IN (SELECT t.topic_id 
                    FROM topics t
                    WHERE t.content_type = 'rvf')
like image 136
a_horse_with_no_name Avatar answered Oct 06 '22 23:10

a_horse_with_no_name


This should work if you are using 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...

like image 27
Abe Miessler Avatar answered Oct 06 '22 23:10

Abe Miessler