逐行分组并为每个分配名称

时间:2015-11-18 10:25:58

标签: php mysql

我有这张桌子

id   ins  sec  div  subject  subjectHour  level
1     1    1    7   subName       5      level 1
2     1    2    7   subName2      4      level 1
3     1    2    7   subName3      4      level 2
4     1    1    7   subName4      6      level 2

我想要输出像

这样的东西

1级科目
SUBNAME
subName2

2级科目
subName3
subName4

mysql加入4个表

    $displayMat = $db->prepare('SELECT
     a.id, a.ins_id, a.sub_name, a.subHour, a.level,
     b.id, b.ins_name,
     c.id, sec_name,
     d.id, div_name
     FROM ins_subjects AS a
     INNER JOIN institutes AS b
     INNER JOIN ins_sections AS c
     INNER JOIN ins_division AS d
     WHERE a.ins_id=?
     GROUP BY a.id;
 ');

这是循环

$displayMat->bind_param('i', $inId);
  if ($displayMat->execute()) {
  $results = $displayMat->get_result();
  while ($m = mysqli_fetch_array($results)) {
<li>
  <div class="col-xs-3"><?php print $m['sub_name']; ?></div>
  <div class="col-xs-3"><?php print $m['ins_name']; ?></div>
  <div class="col-xs-3"><?php print $m['sec_name']; ?></div>
  <div class="col-xs-3"><?php print $m['div_name']; ?></div>
</li>
}

1 个答案:

答案 0 :(得分:0)

你需要一些连接条件,而GROUP BY似乎是多余的。

从这样的事情开始: -

SELECT a.id, a.ins_id, a.sub_name, a.subHour, a.level,
        b.id, b.ins_name,
        c.id, sec_name,
        d.id, div_name
FROM ins_subjects AS a
INNER JOIN institutes AS b ON a.ins_id = b.id
INNER JOIN ins_sections AS c ON a.sec_id = c.id
INNER JOIN ins_division AS d ON a.div_id = d.id
ORDER BY a.level, a.sub_name

您可以依次阅读每一行。存储级别,当级别从上一行更改时,您输出级别。

修改

粗略地在php中完成,类​​似这样(这里没有使用列表)

<?php
$displayMat->bind_param('i', $inId);
if ($displayMat->execute()) 
{
    $results = $displayMat->get_result();
    $prev_level = '';
    while ($m = mysqli_fetch_array($results)) 
    {
        if ($prev_level != $m['level'])
        {
            echo $m['level'];
        }
        $prev_level = $m['level'];
        ?>
          <div class="col-xs-3"><?php print $m['sub_name']; ?></div>
          <div class="col-xs-3"><?php print $m['ins_name']; ?></div>
          <div class="col-xs-3"><?php print $m['sec_name']; ?></div>
          <div class="col-xs-3"><?php print $m['div_name']; ?></div>
        <?php
    }
}