Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two tables in an UPDATE statement?

Tags:

sql

mysql

Consider the following tables: "users" and "tweets"

user_id name             tweet_id user_id tweet        spam
-----------------        ----------------------------------
1       SUSPENDED        1        1       lorem ipsum  0
2       foo              2        1       dolor        0
3       bar              3        2       samet        0
4       SUSPENDED        4        1       stunitas     0
                         5        3       hello        0
                         6        4       spamzz!      0

I want to update the "tweets" table by marking all tweets made by SUSPENDED users, as spam. So in the above example, tweets with tweet_id 1, 2, 4 and 6 would be marked as spam by updating the "spam" value from 0 to 1.

I'm having trouble joining the two tables. Until now, I've only had to join in SELECT statements, but this seems more troublesome:

UPDATE tweets SET spam = 1 WHERE tweets.user_id = users.user_id 
AND users.name = 'SUSPENDED'

This surely isn't working...who could point me in the right direction?

like image 975
Pr0no Avatar asked Mar 31 '12 15:03

Pr0no


People also ask

Can you do a join in an UPDATE statement?

An UPDATE statement can include JOIN operations. An UPDATE can contain zero, one, or multiple JOIN operations. The UPDATE affects records that satisfy the JOIN conditions.

Can you UPDATE 2 tables with a UPDATE statement in SQL?

In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause.

Can we use group by in UPDATE statement?

Can we use GROUP BY clause in an UPDATE statement? Then No.

How do I join two tables in a query?

You create an inner join by dragging a field from one data source to a field on another data source. Access displays a line between the two fields to show that a join has been created. The names of the tables from which records are combined.


2 Answers

You're on the right track, but you need to specify a JOIN between the tables:

UPDATE tweets JOIN users ON tweets.user_id = users.user_id
  SET tweets.spam = 1
WHERE users.name = 'SUSPENDED'
like image 154
Michael Berkowski Avatar answered Oct 15 '22 21:10

Michael Berkowski


This should do it:

UPDATE tweets
INNER JOIN users ON (users.user_id = tweets.user_id)
SET spam=1
WHERE users.name='SUSPENDED'

You can generally use JOIN the same in an UPDATE as you can in a SELECT. You wouldn't be able to join a table to itself in an UPDATE, and there are some other little quirks, but for basic stuff like this it'll work as you'd expect.

like image 25
VoteyDisciple Avatar answered Oct 15 '22 22:10

VoteyDisciple