我正在尝试获取每个类(class)的名称、该类(class)的学生以及分配给该类(class)的科目。
这里,问题是由 ORDER BY
引起的,我已将 ORDER BY
分配给 student.id
。
这会导致主题行重复。
如果未分配 ORDER BY
,则按预期提取主题行,且不重复,但学生行重复。
表格结构
学生
id | Rid | class | name
================================
1 | 1 | 1 | John
2 | 2 | 1 | Harsita
类别
id | title
==============
1 | One
2 | two
3 | three
主题
id | title
===============
1 | science
2 | math
3 | english
4 | social
5 | hpe
类(class)主题
id | class | subject
===========================
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 1 | 4
要求是
class: One
Science | Math | English | Social | Hpe |
John | Harsita
但是我得到了什么
如果将 ORDER BY
分配给 student.id
class: One
Science | Math | English | Social | Hpe | Math | English | Social | Hpe | Science |
John | Harsita |
如果ORDER BY
尚未分配给student.id
class: One
Science | Math | English | Social | Hpe |
John | Harsita | John | Harsita | John | Harsita | John | Harsita | John | Harsita |
我尝试使用GROUP BY
到subject.id
,它只显示一个学生(第一行:John)。问题出在哪里?如何在不使用 subquery
或 GROUP_CONCAT
代码 - php 和 mysql(使用 ORDER BY)
//mysql query
SELECT
DISTINCT class_subject.class,
subject.title AS sub,
student.name AS stdt,
class.title AS class
FROM
student
INNER JOIN class_subject ON class_subject.class=student.class
INNER JOIN subject ON subject.id=class_subject.subject
INNER JOIN class ON class.id=student.class
WHERE
student.class=:cid;
//php
$class='';
$stdt='';
$sub='';
$results = Array();
while($row=$result->fetch(PDO::FETCH_ASSOC)){
if ($row['class'] != $class){
$class = $row['class'];
echo "Class: ".$class."<br/>";
}
if ($row['sub'] != $sub){
$sub = $row['sub'];
echo $sub." | ";
}
$results[]=$row;
}
echo "<br/>";
foreach ($results as $row) {
if ($row['stdt'] != $stdt) {
$stdt = $row['stdt'];
echo $stdt." | ";
}
}
最佳答案
查看您的预期结果样本,您似乎需要名称和主题的聚合结果
SELECT
group_concat( subject.title) AS sub,
group_concat(student.name) AS stdt,
class.title AS class
FROM
student
INNER JOIN class_subject ON class_subject.class=student.class
INNER JOIN subject ON subject.id=class_subject.subject
INNER JOIN class ON class.id=student.class
WHERE student.class=:cid
group by class.title
使用聚合函数和组,您可以在同一行上显示聚合结果
关于php - mysql join重复行,order by引起的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52148003/