MySQL标记系统 - 每月最热门的关键字

时间:2014-01-29 19:30:28

标签: mysql sql subquery greatest-n-per-group tagging

我有一个“Has-many-through”表keyword_sentence,其中包含从句子到关键字的链接。

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`)
)

如何每周获得前5个关键字?

我想知道每周使用哪keyword_id个,所以我可以关注趋势项目。我目前有以下查询,但不太正常。

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

5 个答案:

答案 0 :(得分:3)

尝试此查询

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

希望这有帮助

答案 1 :(得分:1)

你试过这个问题吗?

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

或没有DISTINCT

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

然后,如果你每周有五个或更多,他们出现了, 我希望这能帮到你!

答案 2 :(得分:0)

你试过这个吗?

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;

答案 3 :(得分:0)

按基本计数,按关键字和周分组: -

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

答案 4 :(得分:0)

我不清楚你是在寻找一个月或一周,所以我为MONTH做了。 这是代码:

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

小提琴:http://www.sqlfiddle.com/#!2/d76c5d/8/0