2

假设我有一个名为 students 的表,其中包含所有学生的列表。每个学生可以有许多课程存储在另一个表中,由学生 ID 标识。

我想做一个查询,该查询将从学生表中获取包含学生信息的行,并在一个查询中获取他的所有课程。我想要的输出是这样的:

Array
(
    [0] => Array
        (
            [id] => 5
            [firstName] => Bob
            [lastName] => Smith
            [email] => ....
            [courses] => Array
                (
                    [0] => Array
                        (
                            [id] => 30
                            [name] => Test Course
                            [price] => 400
                        )

                    [1] => Array
                        (
                            [id] => 30
                            [name] => Test Course 2
                            [price] => 300
                        )

                )

        )

)

要获取学生的信息,我会执行以下查询:

SELECT * FROM students WHERE something ='something'

为了获得学生的课程,我会这样做:

SELECT * FROM courses WHERE studentId = '5'

是否可以同时执行两个查询并获得像上面的数组一样的输出,或者我是否必须遍历每个学生并获取其课程,然后手动将其附加到数组?

4

3 回答 3

1

您可以通过将表连接在一起来做到这一点:

select s.*, c.*
from students s join
     courses c
     on s.studentid = c.studentid
where s.something = 'something'

如果您希望学生信息在一行,课程在另一行,那么这是不可能的。所有行必须具有相同的列。

于 2012-05-12T17:24:53.357 回答
1
$query = "select * from students inner join courses on studentID = '5' where something  = 'something'"; 
$result = mysql_db_query ($dbname, $query, $link); 
$id = $row[0]; # corresponding to row in students database
$firstName= $row[1]; # corresponding to row in students database
$lastName = $row[2]; # corresponding to row in students database
$email = $row[3]; # corresponding to row in students database
while($row = mysql_fetch_array($result)) {
  echo 'id: '.$row[id];
  echo '<br>';
  echo 'name: '.$row[name];
  echo '<br>';
  echo 'price: '.$row[price];
  echo '<br>';
}
于 2012-05-12T17:28:03.770 回答
1

基本上新代码将是:

$query = "select * from students"; 
$result = mysql_db_query ($dbname, $query, $link); 
while($row = mysql_fetch_array($result)) {
   $id = $row[0]; # corresponding to row in students database
   $firstName= $row[1]; # corresponding to row in students database
   $lastName = $row[2]; # corresponding to row in students database
   $email = $row[3]; # corresponding to row in students database
   echo 'id: '.$id;
   echo '<br>';
   echo 'firstName: '.$firstName;
   echo ' ';
   echo 'lastName: '.$lastName;
   echo '<br>';
   echo 'email: '.$email;
   echo '<br>';
   $query = "select * from courses where id  = '".$id."'"; 
   $result2 = mysql_db_query ($dbname, $query, $link); 
   while($row2 = mysql_fetch_array($result2)) {
     echo 'name: '.$row2[1]; # corresponding to row in courses database
     echo '<br>';
     echo 'price: '.$row2[2]; # corresponding to row in courses database
     echo '<br>';
   }
}
于 2012-05-12T17:57:22.327 回答