逗号分隔字段的唯一值计数(PHP-MySQL)

逗号分隔字段的唯一值计数(PHP-MySQL),php,mysql,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 interest_id interest_name 1 a 2 b 我需要根据计数得到唯一的“地点”和“兴趣”值。 因此,“place”的输出是 因此,“利息”的输出是 在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
interest_id interest_name 
1           a
2           b
我需要根据计数得到唯一的“地点”和“兴趣”值。 因此,“place”的输出是

因此,“利息”的输出是

在PHP Mysql中有这样做的方法吗

到目前为止,我已经能够得到简单的列数据

SELECT place, 
COUNT( * ) AS num 
FROM testtab 
GROUP BY place 
ORDER BY COUNT( * ) DESC

由于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
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

在当前的配置中,我认为您不能在一个查询中完成这项工作:您必须运行一个查询来获取不同的可能值,然后使用这些值来计算出现的次数。如果您能够正确地规范化这些数据,这将很容易。这里使用的逗号分隔格式与大多数数据库设计实践背道而驰,因为查询起来既困难又昂贵。