这是一个假设的问题。如果我有来自3个独立的sql db查询的3个数组,这些数组都与另一个相关。例如......
//db
schools
id | school_name
classes
id | class_name | school_id
students
id | student_name | class_id
我想在这样一个巨大的列表中显示所有内容......
//php
foreach(schools as school){
echo '<h1>' . $school->school_name . '<h1>';
foreach(classes as class){
if($class->school_id == $school->id){
echo '<h2>' . $class->class_name . '<h2>';
foreach(students as student){
if($student->class_id == $class->id){
echo '<h3>' . $student->student_name . '<h3>';
}
}
}
}
}
我必须进行3次数据库调用。有没有办法在单个数据库查询中获取所有这些信息?就像数组中的数组中的数组然后以某种方式循环?或者这是最好的方法吗?
答案 0 :(得分:1)
你可以进行一次加入,每次加入一次。你想要一切或任何类型的过滤器吗?
答案 1 :(得分:1)
您可以加入这些表格,以获得一个包含展平数据的大数组。循环遍历此数据时,您可以检查上一条记录的ID是否仍与当前记录的ID匹配。如果没有,您可以输出新的标题。但重要的是,结果集已正确排序。
SELECT
s.id AS school_id,
s.school_name,
c.id AS class_id,
c.class_name,
st.id AS student_id,
st.student_name
FROM
schools s
INNER JOIN classes c ON c.school_id = s.id
INNER JOIN students st ON st.class_id = c.id
ORDER BY
s.id,
c.id,
st.id
如果你把它全部放在扁平结构中,你甚至可以把它变成一个嵌套的数组结构:
foreach ($resultset as $row)
{
$schools[$row->school_id]->school_name =
$row->school_name;
$schools[$row->school_id]->classes[$row->class_id]->class_name =
$row->class_name;
$schools[$row->school_id]->classes[$row->class_id]->students[$row->student_id]->student_name =
$row->student_name;
}
var_dump($schools);
之后,您仍然可以使用嵌套的for循环来处理数组,但它将以更有效的方式,因为数据已经被整理出来:类已经添加到他们所属的学校,并且学生已添加到正确的课程中。
答案 2 :(得分:0)
您可以在一个SQL查询中完成所有操作,可能类似于:
SELECT schools.schoolname, classes.class_name, students.student_name
FROM
schools INNER JOIN classes ON (schools.id = classes.school_id)
INNER JOIN students ON (classes.id = students.class_id)
ORDER BY 1, 2;
然后你可以在一个循环中遍历结果集,但是你可能想要添加一些逻辑,以便每次更改时只显示学校名称和类名。
答案 3 :(得分:0)
$res = mysql_query('SELECT school_name, class_name, student_name, sc.id AS scid, c.id AS cid, st.id AS stid FROM schools sc LEFT JOIN classes c ON (sc.id = c.school_id) LEFT JOIN students st ON (c.id = st.class_id) ');
$arr = array();
while ($v = mysql_fetch_assoc($res)) {
$arr[$v['school_name']][$v['class_name']][$v['stid']] = $v['student_name'];
}
print_r($arr);
答案 4 :(得分:0)
<?php
try {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=school", "username");
} catch (PDOException $e) {
echo "PDO Connection failed: " . $e->getMessage();
exit(1);
}
$sql = <<<SQL
SELECT schools.school_name, classes.class_name, students.student_name
FROM
schools INNER JOIN classes ON (schools.id = classes.school_id)
INNER JOIN students ON (classes.id = students.class_id)
ORDER BY 1, 2;
SQL;
$result = $pdo->query($sql);
if ($result == false) {
die("query failed?!");
}
$school = "";
$class = "";
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($school != $row['school_name']) {
$school = $row['school_name'];
echo "\nSchool: $school\n\n";
}
if ($class != $row['class_name']) {
$class = $row['class_name'];
echo " Class: $class\n\n";
echo " Student list:\n";
}
echo " {$row['student_name']}\n";
}