2

我的数据如下所示:

            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 中寻找一种方法来做到这一点。

4

2 回答 2

3

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

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 开始。一个单词在一个空格之后开始,所以我在评论的开头放了一个空格。

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

于 2013-04-04T20:07:39.383 回答
0

这是一个 hack,但您也可以使用 SQLite 的表值函数来解决这个问题:

select value from (
    select
        '["' || replace(trim(title), '"', '') || '"]' as arr
    from story limit 2500000
    ) e, json_each(e.arr)

但请注意 - 您可能会注意到您的列中有很多字符可能会破坏 JSON 解析并引发 JSON 解析错误。

在这种情况下,您可能必须删除一些控制字符:

select value from (select
'["' || replace(replace(replace(replace(replace(replace(trim(title), '"', ''), CHAR(10), ""), CHAR(13), ''), "  ", ""), "\", ""), ' ', '","') 
|| '"]' as arr
from your_table limit 2500000
) e, json_each(e.arr)

为了更容易调试,您可以使用限制和偏移的组合(例如limit 1000000 offset 2200000)来帮助您找到问题行,然后将该字符替换为空字符串。

于 2020-08-31T04:24:54.177 回答