我一直在使用stackoverflow来帮助我,但是现在我很难过 - 希望我能在这个问题上得到一些指导:
我有两张桌子,一张包含NFL分区,另一张包含NFL队伍。它们通过division_id字段连接(Divisions表上的主键,Teams表上的外键)。
我想要做的是在查询中加入表格并输出分组小组。我可以在PHP中使用两个单独的查询/循环完成此操作,但我想知道如何通过在单个查询中连接两个表来实现此目的。
这就是我所拥有的:
$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name,
Teams.name FROM Divisions INNER JOIN Teams ON
Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";
if( $result = $db->query($query) ){
while( $row = $result->fetch_object() ){
// here is where I'm stuck
}
}
我试图让最终输出看起来类似于:
AFC North
克利夫兰布朗队
匹兹堡钢人队
巴尔的摩乌鸦队
辛辛那提孟加拉虎
AFC East
布法罗比尔
迈阿密海豚队
等。
主要感谢任何可以帮助我的人!我在两年多的时间里没有做过任何编程,只是重新开始编程。
答案 0 :(得分:1)
遍历行并在division_id
更改时输出新标头:
$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name,
Teams.name AS teamName FROM Divisions INNER JOIN Teams ON
Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";
if ($result = $db->query($query)) {
$division = "";
while ($row = $result->fetch_object()) {
if ($division != $row["division_id"])
{
$division = $row["division_id"];
echo "<br /><h2>{$row["conference"]}</h2>";
}
echo "{$row["teamName"]}<br />";
}
}
答案 1 :(得分:0)
$result = array();
if( $result = $db->query($query) ){
while( $row = $result->fetch_object() ){
if(empty($result[$row['division_id']])
{
$result[$row['division_id']] = $row;
}
$result[$row['division_id']]['teams'][] = $row;
}
}
print_r($result);
答案 2 :(得分:0)
你可以循环检查它是否是同一个分区。
如果它是一个新的部门,请写下它并<br />
$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name,
Teams.name as teamName FROM Divisions INNER JOIN Teams ON
Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";
if( $result = $db->query($query) ){
$lastDivision = -1;
while( $row = $result->fetch_object() ){
if($lastDivision != $row["division_id"]){
//here it is a new division,
echo "<b>" . $row["division_id"] . "</b><br />";
}else{
//not a new division so we just continu to write teams
echo $row["teamName"] . "<br />";
}
$lastDivision = $row["division_id"];
}
}