With some help from someone here on Stackoverflow i almost got to the point where the query is perfect. I need some little help adjusting the query to fit my needs, and i hope someone could help me out again.
Here’s the case, i have the following 2 tables :
Tweet
and
Tweet_tags
Every tweet has a tag, and a tweet can have more of the same tags. I want to count how many tweets have the same tag within a time span of week since the tweet was posted.
Here is the query as it is now :
SELECT t.id
, s.tag
, ( SELECT COUNT(1)
FROM twitter.tweet_tags r
JOIN twitter.tweet q
ON q.id = r.tweet_id
WHERE r.tag = s.tag
AND q.date >= t.date
AND q.date <= t.date + INTERVAL 7 DAY
) AS cnt
FROM twitter.tweet t
JOIN twitter.tweet_tags s
ON s.tweet_id = t.id
ORDER
BY cnt DESC
The results of this query are :
| ID | Tag | Cnt |
-------------------------------
| 1 | Testtag | 2 |
| 2 | Testtag | 1 |
| 3 | tweettag3 | 1 |
| 4 | tweettag2 | 1 |
I have the testtag 2 times in my database, so the first result is correct, tweettag3 and tweettag2 are in my database 1 time so thats good as well, but these will probably also show multiple results when i add them again. I tried using DISTINCT on s.tag to get rid of the duplicate result, however this gives me a syntax error.
So how i want it to be is :
| ID | Tag | Cnt |
-------------------------------
| 1 | Testtag | 2 |
| 2 | tweettag3 | 1 |
| 3 | tweettag2 | 1 |
Could someone please help me out on this? If you need more information please say so!
Thanks !!
Edit :
This is how the tables look:
Tweet
---------------
ID
Message
users_id
Date
Tweet_tags
---------------
id
tag
tweet_id
You can just use
select distinct, so the query would be:Just remove the id field from the select.
If you want an id, then you can use the MySQL feature of hidden columns to have: