您所写的查询将为每个 ClassName/UserId 对返回一行 - 如果方法类中有两个人,您的查询结果中将有两行。
您可以选择在 php 中将它们组合在一个循环中,或者您可以更改查询以将事物组合在一起。如果您将其视为“我想将给定类名的所有 UserId 分组”,它会建议如何在 SQL 中使用 GROUP BY 子句:
SELECT classes.ClassName, students.UserID
FROM classassociation
JOIN students
ON classassociation.UserID = Students.UserID
JOIN classes
ON classassociation.ClassID = classes.ClassID
WHERE classassociation.ClassID = 1
GROUP BY ClassName;
现在每个 ClassName 都会有一行,但是您仍然需要告诉 MYSQL 如何处理每一行的多个 UserId。在您的情况下,您希望将 UserIds 连接到一个逗号分隔的列表中。令人高兴的是,the manual 中有一个特殊部分仅用于您与GROUP BY 一起使用的功能。在这种情况下,GROUP_CONCAT 给出了预期的结果:
SELECT classes.ClassName, GROUP_CONCAT(students.UserID SEPARATOR ',') AS UersIds
FROM classassociation
JOIN students
ON classassociation.UserID = Students.UserID
JOIN classes
ON classassociation.ClassID = classes.ClassID
WHERE classassociation.ClassID = 1
GROUP BY ClassName;
现在您将获得一个结果集,其中每个 ClassName 有一行,有两列:
ClassName | UserIds
---------------------
Methodology | 1,2
然后你可以编写一个简单的 php 循环来获取查询中的每一行并在你的 html 中生成一个表格行。
如果您查看GROUP_CONCAT 的手册,您会发现您还可以设置 userId 的分组顺序,这可能很有用。
获得查询结果后,php 循环非常简单;您只需要创建一个表,然后为每个结果添加一行:
/*assume your mysql query has returned an array of objects named $result */
// in your html document, create your table with its header
print '<table><thead><tr><th>Class Name</th><th>UserIds</th></tr></thead>';
print '<tbody>';
// now loop through your query results and put stuff into the table
// of course you can monkey around with the table format and what goes in each cell
foreach($result as $row) {
print '<tr><td>'.$row->ClassName.'</td><td>'.$row->UserIds.'</td></tr>';
}
print '</tbody></table>';
这是一个非常简单的例子,但希望能在某种程度上揭开这个过程的神秘面纱。
您的特殊情况看起来查询实际上是获取表格中一个单元格的内容;您可以执行按时间和星期几分组的更宏大的查询,也可以执行少量查询并将结果存储在嵌套数组中,以模拟您希望表的外观。 html 输出在结构上是相同的,但是每个表格单元格都有一个 php 循环。
要让每个单元格显示单独查询的结果的表格,请考虑以下伪代码:
$days = array('Monday', 'Tuesday',...'Friday');
$times = array('9', '10'...);
$weekResults = array();
foreach($days as $day) {
$weekResults[$day] = array();
foreach($times as $time) {
$weekResults[$day][$time] = doQuery($day, $time);
}
}
// now you have nested arrays with a result set for each table cell.
// Rendering the table, you just use the same loops:
renderTableHeader(); // all the <table><thead> stuff
foreach($weekResults as $day) {
print '<tr>'
foreach($day as $time) {
print '<td>';
// output the data from your query like above
// if the formatting is complex, you can even put another table inside the <td>.
print '</td>';
}
print '</tr>';
}
renderTableFooter(); // close tbody and table tags
希望有帮助!