2012-09-06 36 views
0

我有表:計數數據

========================================================== 
|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; 

但結果仍然是錯誤的。請幫我..謝謝:)

+1

什麼是'stem_freq'?未在表格中列出。 – Hamish

+0

@Hamish抱歉,我編輯了它。 –

+0

@JohnWoo依賴於'id_sentence'。 'id_sentence' 0有1個數據等 –

回答

2

如果我理解你的問題,你想在計算freq爲每個不同的id_sentence總和爲特定document_id

嘗試以下SQL:

SELECT id_sentence, SUM(freq) as freq FROM tb WHERE document_id = 1 GROUP BY(id_sentence) 

結果將是與id_sentence數據的行和相應的總freq。之後不需要手動總結事情。

看到這個SQL小提琴:http://sqlfiddle.com/#!2/691ed/8

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組合的計數是。