将表结果连接到各个列

时间:2016-07-07 05:42:22

标签: php mysql

学生表:

Error : Argument 2: cannot convert from 'uint' to 'Android.content.Res.colorStateList'

教师表:

(student_id(PK),student_name,subject_enrolled(FK))

主题表:

(teacher_id(PK),teacher_name,subject_teaches(FK))

如何为此设置正确的JOIN TABLES查询,以便它可以容纳5位不同列的教师:

  

(student_name,teacher_name1,teacher_name2,teacher_name3,teacher_name4,teacher_name5)

     

(由相同的subject_enrolled和subject_teaches产生)

2 个答案:

答案 0 :(得分:0)

当你添加php标签iam使用php分割教师名称列时。检查我的代码

$conn = mysqli_connect(servername, dbusername, dbpassword,database);
 $query=mysqli_query($conn,"SELECT students.student_name,GROUP_CONCAT(teachers.teacher_name) FROM students JOIN teachers WHERE teachers.subject_teaches = students.subject_enrolled GROUP BY students.student_id");
   while($row=mysqli_fetch_array($query)){
$student[]=$row["student_name"];
$teacher[]=$row["GROUP_CONCAT(teachers.teacher_name)"];
    }
  echo'<table><tr><th>Student name</th><th>Teacher name1</th><th>Teacher name2</th><th>Teacher name3</th><th>Teacher name4</th><th>Teacher name5</th>       </tr>';
    $sidebar2 = new MultipleIterator();
        $sidebar2->attachIterator(new ArrayIterator($student));
        $sidebar2->attachIterator(new ArrayIterator($teacher));
          foreach ( $sidebar2 as $value) {
            list($studentname,$teachername) = $value;
         $tarray=explode(",",$teachername);
       echo"<tr><td>$studentname</td>";
      foreach($tarray as $teachern){
      echo"<td>$teachern</td>";
   }
     echo'</tr>';
        }
        echo'</table>';

答案 1 :(得分:0)

根据您的实际表,这可以在单个SQL语句中使用: -

SELECT s.student_name,
        SUBSTRING_INDEX(GROUP_CONCAT(t.teacher_name ORDER BY teacher_id), ',', 1) AS teacher_name1,
        IF(COUNT(t.teacher_id) >= 2, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(t.teacher_name ORDER BY teacher_id), ',', 2), ',', -1), NULL) AS teacher_name2,
        IF(COUNT(t.teacher_id) >= 3, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(t.teacher_name ORDER BY teacher_id), ',', 3), ',', -1), NULL) AS teacher_name3,
        IF(COUNT(t.teacher_id) >= 4, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(t.teacher_name ORDER BY teacher_id), ',', 4), ',', -1), NULL) AS teacher_name4,
        IF(COUNT(t.teacher_id) >= 5, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(t.teacher_name ORDER BY teacher_id), ',', 5), ',', -1), NULL) AS teacher_name5
FROM student s
LEFT OUTER JOIN teacher t ON s.subject_enrolled = t.subject_teaches
GROUP BY s.student_id

但是我关心的是你的表格描述。您的学生表具有student_id作为主键,然后是subject_enrolled的字段。这表明您为每个学生提供了多个student_ids,或者subject_enrolled是他们注册的所有科目的分隔字段。

我上面的SQL假设学生ID不是主键,因此每个学生/学生ID可以有多行。