问题描述
||
我有两个表:
TRIPS
-----------------
tripID | clientID
和
LEGS
--------------------------------
legID | depart | arrive | tripID
TRIPS与LEGS有一对多的关系,因为每个tripID
有几个legID
\。我需要以以下格式显示它们:
Trip tripID1:
Leg legID1: depart1 - arrive1
Leg legID2: depart2 - arrive2
Trip tripID2:
Leg legID3: depart3 - arrive3
Leg legID4: depart4 - arrive4
etc...
我已经能够通过WHILE()
循环遍历legID,但是在将LEGS循环嵌入TRIPS循环中时遇到了麻烦。我的查询是:
<?PHP
$legsQuery = \"SELECT trips.tripID,legs.depart,legs.arrive FROM legs,trips WHERE `trips`.tripID = `legs`.tripID\";
$legsQueryResult = MysqL_query($legsQuery) or die(\"QUERY LEG ERROR: \" . MysqL_error());
while($row = MysqL_fetch_assoc($legsQueryResult)) {
print_r($row);
}
?>
解决方法
添加
order by
子句以按旅行ID排序
创建$lastTripID
变量以检查何时从“新行程”获得“腿”
[推荐]使用join
从多个表中选择数据
码:
<?php
$legsQuery = \"
select
trips.tripID,legs.depart,legs.arrive
from
legs
inner join trips on trips.tripID = legs.tripID
order by
trips.tripID
\";
$legsQueryResult = mysql_query($legsQuery) or die(\"QUERY LEG ERROR: \" . mysql_error());
$lastTripID = null;
while ($row = mysql_fetch_assoc($legsQueryResult)) {
if ( $row[\'tripID\'] !== $lastTripID ) {
echo $row[\'tripID\'],\"\\n\";
$lastTripID = $row[\'tripID\'];
}
print_r($row);
}