我在我的數據庫中有逗號分隔的字段base_users
。如何查詢以計算該組的totaluser
?如果數據不在逗號分隔的字段中,我沒有問題來計算totaluser
。計算逗號分隔值的用戶數
SELECT COUNT(base_u_id) AS totaluser
FROM base_users
WHERE base_u_group =".$row['base_gp_id']."
1)base_users |base_u_id | base_u_name | base_u_group | ------------------------------------------ | 1 | username1 | 1, 2, 4 | | 2 | username2 | 3 | | 3 | username3 | 3, 4 | | 4 | username4 | 1, 4 | 2)base_groups | base_gp_id | base_gp_name | ------------------------------ | 1 | group1 | | 2 | group2 | | 3 | group3 | | 4 | group4 | | 5 | group5 |
從上面的示例數據庫,我預期的結果將是:
Total User of group1 = 2
Total User of group2 = 1
Total User of group3 = 2
Total User of group4 = 3
Total User of group5 = 0
這是我到目前爲止已經試過:
<?php
$getUser = base_executeSQL("SELECT * FROM base_users");
while($row_getUser = base_fetch_array($getUser))
{
$explodeData = explode(", ",$row_getUser['base_u_group']);
foreach($explodeData as $data)
{
$getUserGroupSQL = base_executeSQL("SELECT COUNT(base_u_id) AS totaluser FROM base_users as user, base_groups as gp WHERE gp.base_gp_id ='".$data."' ");
while($UserGroupProfile_row = base_fetch_array($getUserGroupSQL))
if (base_num_rows($getUserGroupSQL)!= 0)
$totaluser = $UserGroupProfile_row["totaluser"];
elseif (base_num_rows($getUserGroupSQL)== 0)
$totaluser = 0;
}
}
?>
總僅僅是逗號+ 1(或用逗號字符串的長度和字符串的長度沒有逗號,+ 1之間的差)的數目。現在看到正常化 – Strawberry
更好地修復損壞的分貝設計。它需要規範化 –
@Strawberry我發現[這](http://stackoverflow.com/questions/7020001/how-to-count-items-in-comma-separated-list-mysql)。你是這個意思嗎? – Sollo