Echo results of a complicated INNER JOIN query with multiple tables

倖福魔咒の 提交于 2020-01-05 07:02:50

问题


This is my first question here. I have a complicated SQL database and I need to join different tables which have the same column names.

"event" is a sports match. It contains tournament_stageFK which is linked to tournament_stage table, which contains tournamentFK which is linked to tournament table, which contains tournament_templateFK which is linked to tournament_template table, which contains sportFK which is linked to sport table.

So in order to find out what sport the match is from, I need to do an inner join, otherwise I'd have to open the database millions of times. The only way to do it is this, but I don't know how to display the results. My poor attempt to echo the results is below:

$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>";
}

回答1:


You need to use column aliases and access those in your fetch call. Instead of event.*, be explicit about the columns you need:

$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>";
}



回答2:


Your result is fetched as an array indexed by column name, which is "name" for several of your columns... the table name sport, country, template, etc is not part of the returned index. So you need to provide column names that will be unique

Set an alias for each of your columns (e.g. SELECT sport.name AS sport_name) then reference it by its alias within your echo (e.g. $result['sport_name']).



来源:https://stackoverflow.com/questions/8667590/echo-results-of-a-complicated-inner-join-query-with-multiple-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!