【问题标题】:Search query like twitter trending topics搜索查询,如 twitter 热门话题
【发布时间】:2013-05-24 00:20:42
【问题描述】:

我需要 MYSQL 搜索查询来从我的表中获取热门话题,下面是我需要的说明

+----+---------+-----------------------------+
| ID | ID_user | text                        | 
+----+---------+-----------------------------+
| 1  | bruno   | michael jackson is dead     |
| 2  | thomasi | michael j. moonwalk is dead |
| 3  | userts  | michael jackson lives       |
+----+---------+-----------------------------+

我要查询表中重复次数最多的单词,限制前10个,结果可能是这样的:

+-------+------------+
| count | word       |
+-------+------------+
| 3     | michael    |
| 2     | dead       |
| 2     | jackson    |
| 1     | j.         |
| 1     | lives      |
| 1     | moonwalk   |
+-------+------------+

但我只想搜索重复超过 10 次的单词,在这种情况下没有出现任何单词,但如果重复单词的条件是 2,它将只显示 'michael' 和 'dead',而忽略 'is'因为我不想要长度少于 2 个字符的单词,以及一个短语的单词,所以我需要这样:

+-------+-----------------+
| count | word            |
+-------+-----------------+
| 2     | michael jackson |
| 2     | dead            |
+-------+-----------------+

【问题讨论】:

  • 这里有一个基本的误解:RDBMS 旨在处理字段内容,而不是处理字段内容。虽然可以创建这样的查询,但它很可能是在 DB 中处理它的次优解决方案

标签: php mysql twitter trending


【解决方案1】:
CREATE TEMPORARY TABLE counters (id INT);
-- insert into counters as much as you like (values here means "number of repeats"
INSERT INTO counters VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9),(10),
                           (11),(12),(13),(14),(15),(16),(17),(18),(19),(20),
                           (21),(22),(23),(24),(25),(26),(27),(28),(29),(30);

  SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(texts.text,' ',counters.id),' ',-1) AS word,
         COUNT(counters.id) AS counter
    FROM texts
         INNER JOIN counters ON (LENGTH(text)>0 AND SUBSTRING_INDEX(SUBSTRING_INDEX(text,' ',counters.id),' ',-1) <> SUBSTRING_INDEX(SUBSTRING_INDEX(text,' ',counters.id-1),' ', -1))
   WHERE length(SUBSTRING_INDEX(SUBSTRING_INDEX(texts.text,' ',counters.id),' ',-1)) > 2
GROUP BY word
  HAVING COUNT(counters.id) > 1
ORDER BY counter desc;

但效率不高,不应该那样做

编辑:

  SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(texts.text,' ',counters.id),' ',-1) AS word,
         COUNT(counters.id) AS counter
    FROM texts
         INNER JOIN counters ON (LENGTH(text)>0 AND SUBSTRING_INDEX(SUBSTRING_INDEX(text,' ',counters.id),' ',-1) <> SUBSTRING_INDEX(SUBSTRING_INDEX(text,' ',counters.id-1),' ', -1))
   -- exclude words list
   WHERE SUBSTRING_INDEX(SUBSTRING_INDEX(texts.text,' ',counters.id),' ',-1) NOT IN ('is', 'of', 'this', 'to')
GROUP BY word
  HAVING COUNT(counters.id) > 1
ORDER BY counter desc;

【讨论】:

  • 帮助很大,但没有得到结果。
  • 那你想要什么结果?我不明白“......以及短语......”
  • 我解释一下。我有一张桌子“帖子”。现在有一列“状态”我需要状态中最常用的词。但我也应该排除“of, this, to etc”之类的词。有什么可以帮到我的吗?
猜你喜欢
  • 1970-01-01
  • 2017-10-07
  • 2015-03-08
  • 2015-09-10
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
相关资源
最近更新 更多