几乎所有的帖子和答案都建议并推荐JOINS
而不是sub queries
来提高性能。因此,尽管JOINS
已解决了问题,但我正在尝试实现sub queries
。在这里,一名学生id
在mark
表中包含多个值。
学生
id | Roll | name
=========================
1 | 1 | Smith
标记
id | std_id | sub_id | th
==================================
1 | 1 | 1 | 60
2 | 1 | 2 | 55
主题
id | title
=============
1 | Science
2 | Math
现在我的要求是在一个div中组合与每个id相关的多个值
Name: Smith
Science: 60
Math: 55
但是对于join
,结果是反复获取
Name: Smith
Science: 60
Name: Smith
Math: 55
我尝试了GROUP BY
到std.id
,但是它仅获取第一行的标记,这里仅获取science
的标记。
$result=$con->prepare(
"SELECT
student.id, student.name
subject.title AS sub,
mark.std_id,
mark.sub_id,
mark.th
FROM student
LEFT JOIN mark ON mark.std_id = student.id
LEFT JOIN subject ON subject.id = mark.sub_id
WHERE student.id=:id;"
) or die($con->error);
$result->bindParam(':id',$_POST['std']);
$result->execute();
while($row=$result->fetch(PDO::FETCH_ASSOC)){
$name=$row['name'];
$sub=$row['sub'];
$th=$row['th']; echo"
<article id='blg_half'>
Name: $name<br/>
$sub : $th
</article>";
}
答案 0 :(得分:1)
您需要GROUP BY和一个汇总函数(GROUP_CONCAT),如下所示:
SELECT
student.id, student.en_name AS name, student.class,
GROUP_CONCAT(CONCAT(subject.title, mark.th))
FROM student
LEFT JOIN mark ON mark.std_id = student.id
LEFT JOIN subject ON subject.id = mark.sub_id
WHERE student.id=:id
GROUP BY student.id