[英]Unique value count of comma separated field (PHP - MySQL)
我有看起来像这样的mysql表:
id place interest
1 place1 a,b,c
2 place2 c,d,e
3 place1 a,e
4 place2 f
5 place2 f
6 place3 g,h
我需要获取按计数排序的唯一“位置”和“兴趣”值。 因此,“地方”的输出为
place2(3)
place1(2)
place3(1)
因此,“兴趣”的输出为
a(2)
c(2)
e(2)
f(2)
b(1)
d(1)
g(1)
h(1)
有没有办法在PHP-Mysql中做到这一点?
因此,到目前为止,我已经能够获得简单的列数据
SELECT place,
COUNT( * ) AS num
FROM testtab
GROUP BY place
ORDER BY COUNT( * ) DESC
由于mysql无法保存数组,因此最好像这样建立一个新表:
interest_id interest_name
1 a
2 b
另一个保持关系:
pk id interest_id
1 1 1
2 1 2
该ID是您主表中记录的ID。
有了这个,您可以轻松使用:
select count(*) from THIRD_TABLE where id = YOUR_ID
你可以这样做。
$place = array();
$interests = array();
foreach($rows as $row){
if (!isset($place[$row["place"]])){
$place[$row["place"]] = 0;
}
$place[$row["place"]]++;
$ints = explode(",", $row["interests"]);
foreach($ints as $int){
if (!isset($interests[$int])){
$interests[$int] = 0;
}
$interests[$int]++;
}
}
这将为您提供从相关字段键入的两个数组,其值为计数。 如果这将成为您应用程序中的常见操作,则按照AliBZ的建议将数据标准化将更有意义。
这是您需要的第一个结果
SELECT place,COUNT(interest)
FROM `testtab`
GROUP by place
ORDER BY COUNT(interest) desc
可以做到这一点:
$inst_row = '';
foreach($rows as $row){
$inst_row .= $row['interests'];
}
$inst_values = explode(',', $inst_row);
$inst_count = array_count_values($inst_values);
// $inst_count will return you count as you want ,print_r it and format it accordingly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.