2013-04-04 73 views
0

我有一个看起来像这样的数据:使用sqlite查找列中最常用的单词?

  movie_id comment 
      1   tom cruise is great 
      1   great action movie 
      2   got teary eyed 
      2   great cast 
      1   tom cruise is hott 

我想返回在评论中最常见的词的功能,基于什么movie_id我选择。所以,如果我查询movie_id = 1,我会得到:

  tom, 2 
      cruise, 2 
      is, 2 
      great, 2 
      hott, 1 
      action, 1 
      movie, 1 

而如果我查询movie_id = 2,我会得到:

  got, 1 
      teary, 1 
      eyed, 1 
      great, 1 
      cast, 1 

我看到使用TSQL一些解决方案,但我从来没有使用过,也没有明白代码。寻找一种在sqlite3中做到这一点的方法。

+0

在SQLite中没有'Split'函数或等价函数,所以这不能在一个简单的查询中完成,您可能需要编写一些代码。也许使用Subtr()函数做一些工作 – Scotch 2013-04-04 19:59:50

回答

2

你可以用一个非常丑陋的查询来做到这一点。

select word, count(*) from (
select (case when instr(substr(m.comments, nums.n+1), ' ') then substr(m.comments, nums.n+1) 
      else substr(m.comments, nums.n+1, instr(substr(m.comments, nums.n+1), ' ') - 1) 
     end) as word 
from (select ' '||comments as comments 
     from m 
    )m cross join 
    (select 1 as n union all select 2 union all select 3 
    ) nums 
where substr(m.comments, nums.n, 1) = ' ' and substr(m.comments, nums.n, 1) <> ' ' 
) w 
group by word 
order by count(*) desc 

这是未经测试的。内部查询需要一个数字列表(这里仅限于3;您可以看到如何添加更多)。然后它检查单词是否在位置n + 1开始。一个词在一个空格之后开始,所以我在评论的开始处放了一个空格。

然后它把这个词拉出来,用于聚合的目的。

+0

M是我猜测的movie_id。什么是数字? – user1956609 2013-04-04 20:18:58

+0

@ user1956609。 。 。 Nums是一个只包含从1开始的整数的表格。我正在使用它来测试注释中的偏移量,以确定一个单词是否正在启动。在这种情况下,它只有3个数字。你可能想要更多的像50或100.你可能已经有一个数字表可用(说在另一个表中的主要ID),你可以使用它。 – 2013-04-04 20:20:20

+0

Gah,我试过instr和charindex在sqlite3中,都没有被识别为一个函数。有另一种获得此功能的方法,还是需要添加自定义功能? – user1956609 2013-04-04 21:01:15