[英]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.