admin

具有多个表的复杂INNER JOIN查询的回显结果

sql

这是我的第一个问题。我有一个复杂的SQL数据库,需要连接具有相同列名的不同表。

“赛事”是一场体育比赛。它包含链接到Tournament_stage表的Tournament_stageFK,后者包含链接到锦标赛表的TournamentFK,包含链接到Tournament_template表的Tournament_templateFK,包含包含SportPK的SportFK。

因此,为了找出比赛的来源,我需要进行内部联接,否则我将不得不打开数据库数百万次。唯一的方法就是这样做,但是我不知道如何显示结果。我对结果的回应很糟糕,如下所示:

$SQL = "SELECT sport.name,
country.name, 
tournament_template.name, 
tournament.name, 
tournament_stage.name, 
event.* 
FROM tournament_template 
INNER JOIN sport
ON tournament_template.sportFK = sport.id 
INNER JOIN tournament ON tournament.tournament_templateFK = tournament_template.id 
INNER JOIN tournament_stage ON tournament_stage.tournamentFK = tournament.id 
INNER JOIN event ON event.tournament_stageFK = tournament_stage.id 
INNER JOIN country ON tournament_stage.countryFK = country.id 
WHERE DATE(event.startdate) = CURRENT_DATE() 
ORDER BY sport.name ASC, 
country.name ASC, 
tournament_stage.name ASC, 
event.startdate ASC";

$result = mysql_query($SQL);

while($get=mysql_fetch_array($result))
{
echo $result['event.name'];
echo "<br>";
}

阅读 184

收藏
2021-07-01

共1个答案

admin

您需要使用列别名并在提取调用中访问它们。而不是event.*,明确需要的列:

$SQL = "SELECT sport.name AS sportname,
country.name AS countryname, 
tournament_template.name AS templatename, 
tournament.name AS tournamentname, 
tournament_stage.name AS stagename, 
/* Use explicit column names instead of event.* */
event.name AS eventname,
event.someothercol AS someother 
FROM tournament_template 
...etc...
...etc...";

// Later...
while($row=mysql_fetch_array($result))
{
  echo $row['eventname'];
  echo "<br>";
}
2021-07-01