用同一句子计算数据

时间:2012-09-06 03:13:24

标签: php mysql

我有桌子:

==========================================================
|id | before | after | freq | id_sentence | document_id  |
==========================================================
| 1 |    a   |   b   | 1    |     0       |      1       |
| 2 |    c   |   d   | 1    |     1       |      1       |
| 3 |    e   |   f   | 1    |     1       |      1       |
| 4 |    g   |   h   | 2    |     0       |      2       |
==========================================================

我希望获得的数据数量取决于id_sentencefreq,因此结果必须为1 2 1 这是代码:

$query = mysql_query("SELECT freq FROM tb where document_id='$doc_id' ");
    while ($row = mysql_fetch_array($query)) {
        $stem_freq = $row['freq'];
        $total = $total+$stem_freq;

但结果仍然是错误的。拜托,帮帮我......谢谢:)

2 个答案:

答案 0 :(得分:2)

如果我理解了您的问题,那么您正在尝试计算特定freq的每个不同id_sentence的{​​{1}}总和。

尝试以下SQL:

document_id

结果将是包含SELECT id_sentence, SUM(freq) as freq FROM tb WHERE document_id = 1 GROUP BY(id_sentence) 和相应总数id_sentence的数据行。之后无需手动总结。

请参阅此SQL小提琴:http://sqlfiddle.com/#!2/691ed/8

答案 1 :(得分:1)

我认为你可以做点什么

SELECT count(*) AS count FROM tb GROUP BY(id_sentence,freq)

进行你想要的计数。你甚至可以做像

这样的事情
SELECT count(*) AS count, id_sentence, freq FROM tb GROUP BY(id_sentence,freq)

知道计数所针对的id_sentence,freq组合。