I have the following “tweets” table:
tweet_id user_id text
---------------------------------------------------
1 2 this is a tweet with (TAG} in it
2 2 tweet without a TAG
3 2 {TAG} another {TAG} tweet
4 4 look at my {TAG} and weep!
I want to count, for each user, the number of tweets that contains {TAG} at least once. The tag could be anywhere in the tweet: at the beginning, in the middle or at the end (read: not followed by a space or anything). The table has millions of records, so I’m looking for an efficient way to do this. My first attempt was
SELECT COUNT(tweet_id) FROM tweets WHERE `text` LIKE '%{TAG}%' AND user_id = 2
but this returns 0 while, in this example, it was expected to return 2. So two questions: (i) what am I doing wrong and (ii) is there a more efficient way to do this?
[EDIT]
I would like to insert the result into the “users” table:
user_id tweets_with_tag
2 2
3 0
4 9
Is it possible to count and insert in the same query?
To Insert:
Edit: If the User table already exists do the following