Php 在mysql中获取指定列中具有相同随机字的记录
我在表中有以下数据:Php 在mysql中获取指定列中具有相同随机字的记录,php,mysql,Php,Mysql,我在表中有以下数据: id Description Category 1 I am Desc with printer main category 2 I am desc with test test category 3 new printer desc third category 4 new
id Description Category
1 I am Desc with printer main category
2 I am desc with test test category
3 new printer desc third category
4 new test category printer category
等等
我想在其描述字段中找到具有相同单词(可以是任何类似于打印机但不预定义的单词)的计数。
对于ex输出,应为:
Total Word which is same
2 printer
2 test
我尝试使用布尔选项的示例,但它没有给出所需的输出
这里有一个例子,我给的是打印机,它可以是任何东西。
我不想在任何地方的查询中指定这个词,因为它可以是任何东西。
输出中只应包含在任何位置具有相同单词的描述
提前感谢。试试这个:
SELECT SUM(IF(Description like '%printer%',1,0)) AS Printer,SUM(IF(Description like '%test%',1,0)) AS Test FROM `yourTable`
这可能会有帮助:)建立一个描述中所有单词的字典
$dbh = new PDO($dsn, $user, $password);
$sql = "SELECT description FROM tableName";
foreach($dbh->query($sql, PDO::FETCH_ASSOC) as $result){
foreach (explode(' ',$result['description']) as $word){
$words[] = $word;
}
}
使用(可选)降序对数组中的重复值进行计数
$wordCount = array_count_values($words);
arsort($wordCount);
然后对数组进行过滤,以消除只出现一次的单词
这将为您提供一个数组,其中单词本身作为索引,出现次数作为值
迭代数组并运行COUNT
查询
foreach($filteredWordCount as $word=>$value){
$countSQL = 'select COUNT(*) as rowCount from tableName where description like "%' . $word . '%" ';
$res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
$count[$word] = $res->fetch()['rowCount'];
}
像前面一样,根据值对数组进行排序,并将其打印出来
arsort($count);
print_r($count);
例如,如果需要行数的条件,则只返回出现在5条以上记录中的单词,您可以这样调整查询
foreach($filteredWordCount as $word=>$value){
$countSQL = 'select COUNT(*) as rowCount from domains where description like "%' . $word . '%" HAVING rowCount > 5';
$res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
$c = $res->fetch()['rowCount'];
if (isset($c)){
$count[$word] = $c;
}
}
这很容易受到SQL注入的攻击,应该使用参数化查询。
foreach($filteredWordCount as $word=>$value){
$countSQL = 'select COUNT(*) as rowCount from domains where description like "%' . $word . '%" HAVING rowCount > 5';
$res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
$c = $res->fetch()['rowCount'];
if (isset($c)){
$count[$word] = $c;
}
}