Question

I have a "Has-many-through" table keyword_sentence which contains links from the sentences to the keywords.

TABLE `keyword_sentence` {
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sentence_id` int(11) NOT NULL,
  `keyword_id` int(11) NOT NULL,
  `created` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `sentence_id` (`sentence_id`),
  KEY `keyword_id` (`keyword_id`)
)

How do I get the top 5 keywords per week?

I would like to see which keyword_id's are being used each week so I can watch for trending items. I currently have the following query which isn't quite working.

SELECT ks.keyword_id
FROM
  keyword_sentence ks
WHERE ks.keyword_id IN (
  SELECT DISTINCT ks2.keyword_id FROM keyword_sentence ks WHERE
  from_unixtime(ks.created) >= CURRENT_DATE - INTERVAL 2 MONTH
  AND 
  from_unixtime(ks.created) < CURRENT_DATE - INTERVAL 1 MONTH
)
ORDER BY COUNT(*) DESC
Was it helpful?

Solution

Try this query

SELECT *
FROM (
    SELECT *, @rowNo := if(@pv = week, @rowNo+1, 1) as rNo, @pv := week
    FROM (
        SELECT keyword_id, COUNT(*), YEARWEEK(FROM_UNIXTIME(created)) AS week
        FROM keyword_sentence
        WHERE 
            FROM_UNIXTIME(created) >= CURRENT_DATE - INTERVAL 2 MONTH
        AND
            FROM_UNIXTIME(created) < CURRENT_DATE - INTERVAL 1 MONTH
        GROUP BY week, keyword_id
        ORDER BY week, COUNT(*) DESC
    ) temp
    JOIN (
        SELECT @rowNo := 0, @pv := 0
    ) tempValue
) tmp
WHERE
    tmp.rNo < 6

Fiddle

Hope this helps

OTHER TIPS

Have you tried this queryies ??

SELECT DISTINCT(keyword_id) FROM tmp WHERE created BETWEEN '2014-01-01' AND '2014-02-01' LIMIT 0, 20;

OR without DISTINCT

SELECT keyword_id FROM tmp WHERE created BETWEEN '2014-01-01' AND '2014-02-01' LIMIT 0, 20;

Then, if you have five or more per week them appeared, I hope this help you!

Have you tried this?

SELECT ks.keyword_id, count(*)
FROM keyword_sentence ks
WHERE from_unixtime(ks.created) >= CURRENT_DATE - INTERVAL 2 MONTH AND 
      from_unixtime(ks.created) < CURRENT_DATE - INTERVAL 1 MONTH
group by ks.keyword_id
ORDER BY COUNT(*) DESC
limit 5;

Just doing a basic count, grouped by keyword and week:-

SELECT keyword_id, WEEK(ks.created) AS theWeek, COUNT(*)
FROM keyword_sentence 
WHERE from_unixtime(created) >= CURRENT_DATE - INTERVAL 2 MONTH
AND from_unixtime(created) < CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY keyword_id, theWeek

Im not clear if you are looking for month or week, so i did it for MONTH. Here is the code:

SELECT keyword_id, MONTH(from_unixtime(created)) AS theMonth, COUNT(*) As keywordCount
FROM keyword_sentence 
WHERE from_unixtime(created) >= CURRENT_DATE - INTERVAL 2 MONTH
AND from_unixtime(created) < CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY keyword_id, theMonth
ORDER BY keywordCount DESC

And the Fiddle: http://www.sqlfiddle.com/#!2/d76c5d/8/0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top