V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
troyl
V2EX  ›  MySQL

一个 MySql 的问题

  •  
  •   troyl · 2014-04-26 13:06:42 +08:00 · 2982 次点击
    这是一个创建于 3650 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我现在有一个表如下图所示:



    documentID 是文章号码
    term 是词语
    score 是词语在文章中出现的次数

    当我执行
    select documentID, score from myIndex where term='children' or term='infant';
    结果如下:

    可以看见有很多 documentID 的重复项,比如第二行和第三行的 documentID 就是一样的

    123 5
    123 3

    有没有办法让 documentID 变成一个,而 score 的值是重复项之和?
    拿第二行和第三行来说,就是:
    123 8

    先行谢过~
    11 条回复    1970-01-01 08:00:00 +08:00
    patosky
        1
    patosky  
       2014-04-26 13:15:14 +08:00
    count(score) group by documentID
    patosky
        2
    patosky  
       2014-04-26 13:15:49 +08:00
    @patosky sum()吧。。。写错了
    troyl
        3
    troyl  
    OP
       2014-04-26 13:16:21 +08:00
    @patosky select documentID, sum(score) as orScore from myIndex where term='children' or term='infant' group by documentID;
    troyl
        4
    troyl  
    OP
       2014-04-26 13:16:34 +08:00
    @patosky 谢谢!
    troyl
        5
    troyl  
    OP
       2014-04-26 13:17:35 +08:00
    @patosky 这次学到了 group by,以前都没接触过==
    Mac
        6
    Mac  
       2014-04-26 13:18:30 +08:00
    @troyl 那可以再学学 group_concat,这货也很有用
    coolicer
        7
    coolicer  
       2014-04-26 13:19:02 +08:00
    你用concat_group和group by将它分组,重复的用distinct去掉。结果出来了再去自己计算。

    大概是这样的结果:
    123 5,3
    xxx 1,2,3,4
    ...

    只能帮到这里了
    coolicer
        8
    coolicer  
       2014-04-26 13:19:26 +08:00
    打完发现已经有几个回答了 = =
    troyl
        9
    troyl  
    OP
       2014-04-26 13:22:10 +08:00
    @patosky 顺便再问一个问题,多个数的和可以用 sum() 函数
    那么如果想求多个数的积呢?
    patosky
        10
    patosky  
       2014-04-26 14:25:18 +08:00   ❤️ 1
    @troyl select documentID, cast(exp(sum(log(score))) as SIGNED) from myIndex group by documentID
    troyl
        11
    troyl  
    OP
       2014-04-26 14:30:16 +08:00
    @patosky 谢谢啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1004 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 20:42 · PVG 04:42 · LAX 13:42 · JFK 16:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.