您好,这是我的查询,我收到了 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
最佳答案
有多种方法可以做到这一点。
使用
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/