[英]count total unique words contained in a field of a resultset
how can I count single words appearing in a field of a resultset? 如何计算结果集中某个字段中出现的单个单词?
example 例
id| myfield 1 | pear apple peach watermelon 2 | lime grapes pear watermelon
I want to get 6 because there are 6 unique words 我想得到6个,因为有6个独特的单词
I don't need a fast query, it is just a statistic calculation that will be executed rarely 我不需要快速查询,它只是一个统计计算,很少执行
thanks! 谢谢!
You can split the results on a space and then add them to an array, such as 您可以将结果拆分到一个空格上,然后将它们添加到数组中,例如
foreach($results as $result)
{
$words = explode(" ", $result['myfield']);
$array = array();
foreach($words as $word)
$array[$word] = true;
}
echo count($array);
Probably a better way, but this is quick and dirty 可能是一种更好的方法,但这既快捷又肮脏
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);
}
I cannot think of a pure SQL solution - MySQL dosen't really like to split a single row nto many. 我想不出一个纯粹的SQL解决方案-MySQL不太喜欢将单行拆分为多行。
A PHP version is easy though: 一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.