如何计算出现在结果集字段中的单个单词?
例如
id| myfield 1 | pear apple peach watermelon 2 | lime grapes pear watermelon
我想获得6,因为有6个独特的单词
我不需要快速查询,它只是一个很少执行的统计计算
谢谢!
答案 0 :(得分:2)
您可以在空格上拆分结果,然后将它们添加到数组中,例如
foreach($results as $result)
{
$words = explode(" ", $result['myfield']);
$array = array();
foreach($words as $word)
$array[$word] = true;
}
echo count($array);
可能是一种更好的方式,但这很快又很脏
答案 1 :(得分: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);
}
答案 2 :(得分: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