计算每个变量出现在表中的次数

时间:2015-10-21 18:06:17

标签: php mysql

基本上,我想知道是否有更好的方法来完成这项具体任务。

基本上,我会在数据库中查询“项目需求”列表 - 这些都是单一的,只出现一次。

然后,我搜索另一张表,找出有多少成员拥有所需的“技能 - 这些技能与项目需求直接相关”。

通过运行第二个查询然后将它们插入到这样的数组中,我完成了我想要做的事情:

function countEachSkill(){
    $return = array();
    $query = "SELECT DISTINCT SKILL_ID, SKILL_NAME FROM PROJECT_NEEDS";
    $result = mysql_query($query) or die(mysql_error());
    $num_rows = mysql_num_rows($result);
        while($row = mysql_fetch_assoc($result)){
            $query = "SELECT COUNT(*) as COUNT FROM MEMBER_SKILLS WHERE SKILL_ID = '".$row['NEED_ID']."'";
            $cResult = mysql_query($query);
            $cRow = mysql_fetch_assoc($cResult);
            $return[$row['SKILL_ID']]['Count'] = $cRow['COUNT'];
            $return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
        }   
    arsort($return);

    return $return; 

}

但我觉得必须有更好的方法(可能使用某种类型的连接?)会在结果集中返回它以避免使用数组。

提前致谢。

PS。我知道mysql_已经折旧了。我不能选择使用它。

3 个答案:

答案 0 :(得分:1)

SELECT P.SKILL_ID, P.SKILL_NAME, COUNT(M.SKILL_ID) as COUNT FROM PROJECT_NEEDS P INNER JOIN MEMBER_SKILLS M
ON P.SKILL_ID=M.SKILL_ID
GROUP BY P.SKILL_ID, P.SKILL_NAME

答案 1 :(得分:0)

您可以测试此查询吗

select project_needs.*,count(members_skills.*) as count  from project_needs 
inner join members_skills
on members_skills.skill_id=project_needs.skill_id Group by project_needs.skill_name, project_needs.skill_id

答案 2 :(得分:0)

我调整了Nriddens的答案,以适应选择的不同,我相信他的调整是好的,因为SKILL_ID是主键

function countEachSkill(){
$return = array();
$query = "
SELECT 
    COUNT(*) AS COUNT,
    PROJECT_NEEDS.SKILL_NAME,
    PROJECT_NEEDS.SKILL_ID
FROM
    (SELECT DISTINCT
        SKILL_ID, SKILL_NAME
    FROM
        PROJECT_NEEDS) AS PROJECT_NEEDS
        INNER JOIN
    MEMBER_SKILLS
ON
    MEMBER_SKILLS.SKILL_ID = PROJECT_NEEDS.SKILL_ID
GROUP BY PROJECT_NEEDS.SKILL_ID";

$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
    while($row = mysql_fetch_assoc($result)){
        $return[$row['SKILL_ID']]['Count'] = $row['COUNT'];
        $return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
    }   
arsort($return);

return $return; 

我在select distinct上进行了subquerying,因为我不相信你有一个带有auto inc主键的专用技能表,如果那里我不会使用子查询。