嗨我有以下表格:
列:word,docNum,频率
示例行:
ana,0,1
bob,1,2
ana,0,3
pen,2,2
我想通过删除重复的行并总结"频率"来更新我的表格。值。 所以输出将是:
ana,0,4
bob,1,2
pen,2,2
我不想使用临时表。你能帮我写一下Mysql查询吗?
答案 0 :(得分:2)
您可以使用两个单独的命令update
和delete
执行此操作:
update table t join
(select word, docnum, sum(frequency) as freq
from table t
group by word, docnum
) tsum cross join
(select @rn := -1) hack
t.frequency = tsum.freq + (@rn := @rn + 1);
delete t
from table t
where not exists (select 1
from table t2
where t2.word = t.word and
t2.docnum = t.docnum and
t2.frequency > t.frequency
);
update
语句将频率设置为每个单词/ docnum对的增加值。 delete
然后删除除最小值之外的所有值。
作为一个说明,我永远不会使用这种逻辑。相反,我只会这样做:
create temporary table tsum as
select word, docnum, sum(frequency) as freq
from table t
group by word, docnum;
truncate table t;
insert into t(word, docnum, frequency)
select word, docnum, freq
from tsum;