计算逗号分隔值的用户数

时间:2015-05-14 07:23:05

标签: php mysql

我的数据库中有逗号分隔的字段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;
    }
}
?>

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT COUNT(u.base_u_id), g.base_gp_name FROM base_users u
INNER JOIN base_groups g ON IF(POSITION(',' IN u.base_u_group) > 0, u.base_u_group LIKE ('".$row['base_gp_id'].",%') OR u.base_u_group LIKE ('%, ".$row['base_gp_id'].",%') OR u.base_u_group LIKE ('%, ".$row['base_gp_id']."'), u.base_u_group = '".$row['base_gp_id']."')
WHERE g.base_gp_id = ".$row['base_gp_id']."

答案 1 :(得分:0)

使用以下逻辑:Just HINT

foreach