假设我有一个名为学生的表,其中包含所有学生的列表。每个学生可以将许多课程存储在另一个表中,并由学生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'
是否可以同时执行两个查询并获得类似上面数组的输出,或者我是否必须遍历每个学生并获取其课程,然后手动将其附加到数组中?
答案 0 :(得分:1)
您可以通过将表连接在一起来完成此操作:
select s.*, c.*
from students s join
courses c
on s.studentid = c.studentid
where s.something = 'something'
如果您希望学生信息在一行而课程在另一行,那么这是不可能的。所有行必须具有相同的列。
答案 1 :(得分: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>';
}
答案 2 :(得分: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>';
}
}