【发布时间】:2022-01-07 10:28:59
【问题描述】:
昨天我熟悉了类似 SQL 的 group_concat() 函数。我有名为“科目”和“成绩”的表格。在subjects中存储了“id、name、subject_type”,在grades中存储了“id、grade、subject_type”。
因此,如果科目的 subject_type = 1,它将显示该类型的所有成绩。
我创建了这样的代码:
<?php
$sqltest1 = "SELECT s.id AS id, s.name AS name, group_concat(g.grade SEPARATOR ',') as grades, s.teacher_1 as teacher_1
FROM subjects s
INNER JOIN grades g ON (g.subject_type = s.subject_type)
GROUP BY s.id";
?>
<table class="table table-bordered">
<thead>
<tr>
<th class="col-1">#</th>
<th class="col-3 text-center">Subject</th>
<th class="col-6 text-center">Grade</th>
<th class="col-1 text-center">Options</th>
</tr>
</thead>
<tbody>
<!-- ###################################################################### -->
<?php
$result = $conn->query($sqltest1);
if ($result->num_rows > 0) {
$i = 1;
// output data of each row
while($row = $result->fetch_assoc()) {
//$id = $row['id'];
echo "<tr>";
echo "<td scope='row'>". $i ."</td>";
echo "<td>". $row['name'] ."</td>";
echo "<td><span class='bg-primary'>". $row["grades"] ."</span></td>";
echo "<td class='text-center'>". $row['teacher_1']."</td>";
echo "</tr>";
$i++;
}
} else {
echo "";
}
?>
<!-- ###################################################################### -->
</tbody>
</table>
所以我的问题是我无法在一列中检索单独的成绩。我想获得给定类型的所有成绩,但要显示为单独的成绩。
【问题讨论】:
-
我不明白。您想在成绩范围内单独 td 吗?
-
您的问题不清楚尝试添加适当的数据样本和预期结果(作为表格文本)
-
@LeandroBardelli 在“成绩”表中,它存储特定科目的成绩(对于 subject_type)。因此,在示例中,我的 subject_type 1 具有等级:“1、2、4、5”,它类似于美国/英国的等级,例如“F、E、B、A”。我想在 td 中将这些成绩作为每个成绩 (
<span>1</span>, <span>2</span>, <span>4</span>) 的单独跨度,因为目前我无法将所有成绩分开。 -
如果您不想将它们分组,为什么要使用
GROUP_CONCAT()? -
感谢@Zimnyjestem,如果我的回答对您有帮助,请不要忘记点赞:)