我有两张桌子:
TRIPS
-----------------
tripID | clientID
和
LEGS
--------------------------------
legID | depart | arrive | tripID
TRIPS与LEGS有一对多的关系,因为每legID
有几个tripID
个。{我需要以下列格式显示它们:
Trip tripID1:
Leg legID1: depart1 - arrive1
Leg legID2: depart2 - arrive2
Trip tripID2:
Leg legID3: depart3 - arrive3
Leg legID4: depart4 - arrive4
etc...
我已经能够通过WHILE()
循环遍历legIDs,但是我在TRIPS循环中嵌入LEGS循环时遇到了麻烦。我的疑问是:
<?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);
}
?>
答案 0 :(得分:1)
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);
}