MYSQL 和 PHP 按字段数据对结果进行分组
我正在尝试根据数据库中日志中的数据创建报告,如下所示:
id | 学生 | 类型 | 标记
1 23494 CAT1 50
2 23495 CAT1 20
3 23494 CAT2 35
4 23495 期中 40
到目前为止,我的 select 语句如下所示:
$res = @mysqli_query ($dbc, "SELECT id, student, type, GROUP_CONCAT(marks) AS mark, GROUP_CONCAT(type) AS types FROM log WHERE class = '1' AND term = '2' GROUP BY student DESC");
// Fetch and print all the records....<br>
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
echo '<tr>
<td align="left">'. $row['student'] .'</td>';
//$exams = split(",", $row['exams']); // 4,3,1,2
$marks = split(",", $row['mark']); // 10,20,40,50
foreach( $marks as $mark ) {
echo '
<td align="left">' . $mark . '</td>
';
}
echo '</tr>';
} //End LOOP
//Then i end table
到目前为止,数据显示如下:
STUDENT | CAT1 | CAT2 |期中考试
23494 50 35
23495 20 40
问题是代码不是安排根据“类型”进行“标记”(查看 MIDTERM 输出中的 id 4 和相应的显示)。
问题:
如何按学生显示结果,然后在适当的单元格/组中显示标记,如下所示:?
学生 | CAT1 | CAT2 |期中考试
23494 50 35
23495 20 ; 40
& nbsp 进步 伙计们。
I am trying to create reports based on data from a log in the database that looks like:
id | student | type | marks
1 23494 CAT1 50
2 23495 CAT1 20
3 23494 CAT2 35
4 23495 MIDTERM 40
My select statement so far looks like this:
$res = @mysqli_query ($dbc, "SELECT id, student, type, GROUP_CONCAT(marks) AS mark, GROUP_CONCAT(type) AS types FROM log WHERE class = '1' AND term = '2' GROUP BY student DESC");
// Fetch and print all the records....<br>
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
echo '<tr>
<td align="left">'. $row['student'] .'</td>';
//$exams = split(",", $row['exams']); // 4,3,1,2
$marks = split(",", $row['mark']); // 10,20,40,50
foreach( $marks as $mark ) {
echo '
<td align="left">' . $mark . '</td>
';
}
echo '</tr>';
} //End LOOP
//Then i end table
So far the data displays like so:
STUDENT | CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40
The problem is that the code is not arranging 'marks' according to 'type' (look at MIDTERM output for id 4 and corresponding display).
Question:
How do i display the results by student, followed by marks in the appropriate cell/group like so:?
STUDENT | CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40
Thanks in Advance Guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,尽量让逻辑远离布局。通常最好的做法是首先收集所需的数据,然后显示它。
使用
GROUP_CONCAT
会使事情变得更加复杂,因为您不知道每个学生会得到多少结果,也无法轻松识别哪些分数属于什么类型。考虑到这一点,我创建了一个解决方案。当然,您仍然需要扩展查询。
First, try to keep logic away from layout. It's generally good practice to first gather the data you need, and then display it.
Using
GROUP_CONCAT
can make things more complicated, since you do not know how many results you will get for each student, nor will you be able to easily identify which marks are of what type.With that in mind I've created a solution. You'll still need to extend the query of course.