2012-06-26 113 views
0

如何計算結果集字段中出現的單個字?計算結果集字段中包含的唯一字總數

例如

 

id| myfield 
1 | pear apple peach watermelon 
2 | lime grapes pear watermelon 

我想6,因爲有6個唯一字

我並不需要一個快速查詢,它只是將很少執行的

統計計算

謝謝!

+0

是「aa」和「aaa」不同的單詞嗎? –

+0

是的!對不起,這個糟糕的例子,我編輯:( – skyline26

回答

2
function uniqueWords ($result, $field) { 
    $words = array(); 
    while ($row = mysql_fetch_assoc($result)) { /* or something else if you use PDO/mysqli/some ORM */ 
     $tmpWords = preg_split('/[\s,]+/', $row[$field]); 
     foreach ($tmpWords as $tmpWord) { 
      if (!in_array($tmpWord, $words)) 
       $words[] = $tmpWord; 
     } 
    } 

    return count($words); 
} 
1

我想不出一個純粹的SQL解決方案 - MySQL真的不想把一行分割成很多。

一個PHP的版本是容易做的:

$sql="CREATE TEMPORARY TABLE words (word VARCHAR(100) PRIMARY KEY)"; 
//run this according to your DB access framework 

$sql="SELECT myfield FROM mytable"; 
//run this according to your DB access framework 
while (true) { 
    //fetch a row into $row according to your DB access framework 
    if (!$row) break; 
    $words=preg_split('/[\s,]+/',$row['myfield']); 
    foreach ($words as $word) { 
    //Escape $word according to your DB access framework or use a prepared query 
    $sql="INSERT IGNORE INTO words VALUES('$word')"; 
    //run this according to your DB access framework 
    } 
} 

$sql="SELECT count(*) AS wordcount FROM words"; 
//run this according to your DB access framework, the result is what you want 


$sql="DROP TABLE words"; 
//run this according to your DB access framework 
2

您可以在空間分割的結果,然後將它們添加到一個數組,如

foreach($results as $result) 
{ 
    $words = explode(" ", $result['myfield']); 

    $array = array(); 
    foreach($words as $word) 
     $array[$word] = true; 

} 
    echo count($array); 

可能是一個更好的辦法,但這種是快而髒