php - 如何使用 for 循环和 union all 按列进行分组

标签 php mysql foreach group-by union

您好,这是我的查询,我收到了 3 条记录,我只想要一条记录,我正在尝试按 studentid 进行分组

foreach ($gdFinaldata['gdskill'] as $skillId => $skillScore){

$filterQuery .= $union_all. "SELECT stu.student_pid

FROM tbl_students stu LEFT JOIN r_job_invitations jbi ON stu.student_email = jbi.email 

LEFT JOIN r_job_scores jsc  ON jsc.student_id = stu.student_pid 

WHERE job_id = ".$jobID."  AND skill_id = ".$skillId." AND gd_score >= ".$skillScore." ";

$union_all=" UNION ALL ";

} //for ends here

记录将如下所示:

SELECT stu.student_pid FROM tbl_students stu LEFT JOIN r_job_invitations jbi ON stu.student_email = jbi.email LEFT JOIN r_job_scores jsc ON jsc.student_id = stu.student_pid WHERE job_id = 88 AND skill_id = 3 AND gd_score >= 1   
UNION ALL
SELECT stu.student_pid FROM tbl_students stu LEFT JOIN r_job_invitations jbi ON stu.student_email = jbi.email LEFT JOIN r_job_scores jsc ON jsc.student_id = stu.student_pid WHERE job_id = 88  AND skill_id = 63 AND gd_score >= 2   
UNION ALL  
SELECT stu.student_pid FROM tbl_students stu LEFT JOIN r_job_invitations jbi ON stu.student_email = jbi.email LEFT JOIN r_job_scores jsc ON jsc.student_id = stu.student_pid WHERE job_id = 88  AND skill_id = 128 AND gd_score >= 3

在此之后,我想添加组,我该怎么做,我尝试这样做:

$groupby = "GROUP BY student_id";
$filterStudents = $conn->query($filterQuery.$groupby);

My issue is still returning 3 records i want to group by student

供引用: enter image description here

最佳答案

有多种方法可以做到这一点。

  • 使用union而不是union all,这将仅保留唯一的条目

    select ...
    union
    select ...
    union
    select ...
    
  • 如果您想保留union all(为什么这样做?),请在您的选择周围使用括号,并在其后附加group by

    select student_pid
    ( select student_pid, student_id from ...
    union all
    select student_pid, student_id from ...
    union all
    select student_pid, student_id from ... ) as t
    group by student_id
    

    你的 PHP 看起来会是这样的

    foreach (...) {
        $filterQuery .= $union_all. "SELECT stu.student_pid, jsc.student_id ..."
        // ...
    }
    
    $outerQuery = "select student_pid ("
    $groupby = ") as t GROUP BY student_id";
    $filterStudents = $conn->query($outerQuery . $filterQuery . $groupby);
    
  • 除了group by之外,您还可以使用distinct,例如

    select distinct student_pid
    ( select student_pid from ...
    union all
    select student_pid from ...
    union all
    select student_pid from ... ) as t
    
  • 将结果收集到数组中,然后使用 array_unique 尽管这是效率最低的,因为它获取所有条目而不是相关部分。

关于php - 如何使用 for 循环和 union all 按列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505901/

相关文章:

php - 在 while 循环中执行函数

在存储过程中调用时,MYSQL SELECT 语句返回 null

php - 将 "INSERT"MySQL 查询转换为 Postgresql 查询

.net - 在 foreach 循环声明中使用 LINQ

javascript - 如何在forEach中使用箭头函数?

c# - 如何跳出 C# 中的 foreach 循环?

PHP - 在 cookie 中存储密码是否安全?

javascript - mPDF - 内联 block 不并排显示

php - 在站点之间共享 Kohana 安装

php - PDO 即使没有绑定(bind)任何参数仍然会得到结果