I have the following tables:
tweets retweets
----------------- ----------------
user_id retweets user_id (etc...)
----------------- ----------------
1 0 1
2 0 1
1
2
2
I want to count the number of retweets per user and update tweets.retweets accordingly:
UPDATE users
SET retweets = (
SELECT COUNT(*) FROM retweets WHERE retweets.user_id = users.user_id
)
I have been running this query two times, but it times out (on tables that are not that large). Is my query wring?
Also see the SQL Fiddle (although it apparently doesn’t allow UPDATE statements): http://www.sqlfiddle.com/#!2/f591e/1
This solution should be much faster than using subqueries for getting the count of tweets of each user (your correlated subquery will execute for each user):