I am trying to fetch each class name, students in this class and subjects assigned to this class.
Here, Problem is caused by ORDER BY
, I have assigned ORDER BY
to student.id
.
This causes subject rows duplication.
If ORDER BY
is not assign, subject rows are fetched as expected, are not duplicate, but student row duplicates.
Table structure
Student
id | Rid | class | name
================================
1 | 1 | 1 | John
2 | 2 | 1 | Harsita
Class
id | title
==============
1 | One
2 | two
3 | three
Subject
id | title
===============
1 | science
2 | math
3 | english
4 | social
5 | hpe
class_subject
id | class | subject
===========================
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 1 | 4
Requirement is
class: One
Science | Math | English | Social | Hpe |
John | Harsita
But what I get
if ORDER BY
is assigned to student.id
class: One
Science | Math | English | Social | Hpe | Math | English | Social | Hpe | Science |
John | Harsita |
if ORDER BY
has not assigned to student.id
class: One
Science | Math | English | Social | Hpe |
John | Harsita | John | Harsita | John | Harsita | John | Harsita | John | Harsita |
I've tried using GROUP BY
to subject.id
, it displays only one student (first row: John). Where is problem ? How can I solve without using subquery
or GROUP_CONCAT
code - php and mysql (with 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." | ";
}
}